简体   繁体   中英

Mysql update if condition of subquery how to

Suppose I have 2 tables


Table 1: users

Attributes: id (int), expires_at (varchar), status (enum)

expires_at could be a DATETIME, or it could be a number (the number of logins the person can perform).

status can be "active", "expiring", "expired", etc..


Table 2: staff

Attributes: id (int), user_id (int), contract (enum)

contract can be either: "chronologically" or "fixed number of times"

If "chronologically", users 's expires_at will have a DATETIME value.

If "fixed number of times", users 's expires_at will have a number value as VARCHAR.


One approach could be to create a scheduled event on MySQL so that, every day, at 11:59am, MySQL will check expires_at and set status as expiring or expired.

I'm looking for something like:

UPDATE users SET status = CASE (SELECT expires_at FROM users WHERE status = "active" AND id IN (SELECT id FROM staff WHERE contract = "fixed number of times")
    WHEN expires_at < 10 AND expires_at > 0 THEN "expiring"
    WHEN expires_at <= 0 THEN "expired"
END

for "fixed number of times" contract, and another similar query for "chronologically". Problem is: the above query's syntax is wrong.

i believe u should use

SELECT user_id FROM staff

not

SELECT id FROM staff

try

UPDATE users 
    SET 
        status = 
            CASE
                WHEN expires_at < 10 AND expires_at > 0 THEN 'expiring'
                WHEN expires_at <= 0 THEN 'expired'
                ELSE status
            END
    WHERE 
        id IN (SELECT user_id FROM staff WHERE contract = "fixed number of times")
        AND status = 'active'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM