2015-09-07 34 views
1

我有這個表在MySQL被稱爲safespot的MySQL查詢其他表狀況PHP

+---------+---------------+ 
| term_id | userid | safe | 
+---------+--------|------+ 
|  1 | 1  | large number, unix timestamp here 
|  1 | 2  | large number, unix timestamp here 
|  1 | 3  | large number, unix timestamp here 
|  1 | 4  | large number, unix timestamp here 
+---------+--------+ 

這是表users

+----+-------------+-------------+ 
| id | userid | cash  | 
+----+-------------+-------------+ 
| 1 |  1  | 100000 | 
| 2 |  2  | 100000 | 
| 3 |  3  | 100000 | 
+----+-------------+-------------+ 

我怎麼可以這樣做

SELECT * FROM `users` where `userid`=1 and `cash`>= 1000 and " userid do not exist in table safespot" or "if the user exists in the safestop table, check if the current timestamp is higher than the safe colum) 

所以基本上做一個查詢,也會返回它,如果userid不存在於保險箱表中,或者如果它存在,那個時間戳高於safe_value。

回答

0
SELECT * FROM users u 
LEFT JOIN safespot s ON s.userid = u.userid 
WHERE 
    u.userid = 1 
    AND u.cash = 1000 
    AND (s.userid IS NULL OR s.safe > UNIX_TIMESTAMP()) 

這將返回用戶那裏

  • 存在safespot對於給定用戶ID的條目,或
  • 有一個條目與va的safespot大於當前時間戳的safe
0
SELECT * FROM `users` WHERE `userid`=1 AND `cash`>= 1000 AND (userid NOT IN (
     SELECT DISTINCT userid FROM safespot 
    ) OR (userid IN (
     SELECT DISTINCT userid FROM safespot WHERE safe < UNIX_TIMESTAMP() 
    ) 
) 
+0

但是,它也必須具備條件,它存在於另一個表中,它必須檢查安全值,因此它比當前時間戳更大? – maria

+1

對不起,我更新了我的答案;-) –

0

使用WHERE NOT EXISTS

SELECT u.* FROM `users` u 
where u.`userid`=1 
and u.`cash` >= 1000 
and (NOT EXISTS (select 1 from safespot where userid <> u.userid) 
or EXISTS (select 1 from safestop where userid = u.userid and safe < CURRENT_TIMESTAMP)); 
+0

但它也必須具備條件,它存在於另一個表中,它必須檢查安全值,因此它比當前時間戳更高? – maria

+1

@maria,如果有幫助,請參閱編輯答案。你只需要添加另一個條件。 – Rahul