簡體   English   中英

mysql-query其他表條件PHP

[英]mysql-query other table condition PHP

我在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)

因此,基本上可以執行一個查詢,如果用戶ID不存在於safespot表中,或者如果確實存在,則該時間戳大於safe_value,該查詢也將返回該查詢。

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

使用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));
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比當前時間戳。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM