Mysql – Default value as expression from other columns

foreign keyMySQL

I have 2 tables:

users

  • user_id (int ai pk)
  • premium

premium_subscription

  • subscription_id (int ai pk)
  • user_id (int) -> fk to user.user_id
  • expiration (datetime)

I would like to implement a boolean value based on the fact if there's a subscription and its expiration date is ahead of the time I made the query.

I made this if statement, that works in a SELECT query. However, I'm not able to implement it as the value of a table.

IF(timestampdiff(SECOND, CURRENT_TIMESTAMP, (SELECT expiration FROM premium_subscription WHERE user_id = *)) > 0, 1, 0);

Is there any way to apply this expression to this column? Thanks in regards! ^^

Best Answer

DEFAULT has a lot of restrictions.

you can use here a daily EVENTs which runs every day and set premium accourdind to the expiration date

DROP EVENT IF EXISTS daily_event;
CREATE EVENT daily_event
ON SCHEDULE EVERY '1' DAY
STARTS '2020-12-12 00:00:01' -- mustbe in the future
DO
    UPDATE users u1
    INNER JOIN premium_subscription ps ON u1.user_id = ps.user_id
    SET premium = IF(NOW() > ps.expiration , 1, 0);

To enable the event scheduler see manual