I have this table in mysql called 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
+---------+--------+
And this is table users
:
+----+-------------+-------------+
| id | userid | cash |
+----+-------------+-------------+
| 1 | 1 | 100000 |
| 2 | 2 | 100000 |
| 3 | 3 | 100000 |
+----+-------------+-------------+
how can i do something like
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)
So basically do a query that also would return it if userid dont exist in safespot table, or if it does, that timestamp is higher than 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()
)
)
Use WHERE NOT EXISTS
like
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())
This returns users where
safespot
for the given userid, or safespot
with the value of safe
greater than the current timestamp.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.