2015-09-07 70 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