mysql-query其他表条件PHP

时间:2015-09-07 15:26:36

标签: php mysql database

我在mysql中有这个名为safespot的表

+---------+---------------+
| 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)

所以基本上做一个查询,如果用户名不存在于safespot表中,也会返回它,或者如果确实存在,则该时间戳高于safe_value。

3 个答案:

答案 0 :(得分: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()
    )
)

答案 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));

答案 2 :(得分: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())

这将返回用户

  • 对于给定的用户ID,safespot中没有条目,或
  • safespot中有一个条目,其值safe大于当前时间戳。