0

When a user buys a license for my product I'm trying to add the number of days remaining (if he has any) to the new 30-day period.

SELECT
    SUM(DATEDIFF(access_expires, CURDATE())) + 30 as access_remaining
FROM wp_woocommerce_downloadable_product_permissions
WHERE
    user_email = 'user@mail.com' AND
    product_id = 8 AND access_expires IS NOT NULL;

UPDATE wp_woocommerce_downloadable_product_permissions
SET
    access_expires = DATE_ADD(CURDATE(), access_remaining)
WHERE
    user_email = 'user@mail.com' AND
    product_id = 8 AND
    access_expires IS NULL

It seems like I can't use access_remaining from my previous query in my second query. Please help, if possible without using join. Using mariadb if it means anything.

Shadow
  • 33,525
  • 10
  • 51
  • 64
J. Locke
  • 11
  • 3

2 Answers2

1

You seem to have imposed odd restrictions on this problem. Are you using strictly /usr/bin/mysql, and cannot use e.g. python or java? Can you assign to a temp variable with := ? Why no JOIN?

Consider using UPDATE with correlated sub-query, as in MySQL/SQL: Update with correlated subquery from the updated table itself .

You chose a perfectly sensible way to model the bookkeeping, by maintaining a calendar expiry date. But consider modeling in a different way: you might store (begin, end) dates for which a customer is paid up. You might find it makes some queries easier to phrase.

J_H
  • 17,926
  • 4
  • 24
  • 44
1

Notice the use of a "user variable" @ar:

SELECT
    @ar := SUM(DATEDIFF(access_expires, CURDATE())) + 30 as access_remaining
FROM wp_woocommerce_downloadable_product_permissions
WHERE
    user_email = 'user@mail.com' AND
    product_id = 8 AND access_expires IS NOT NULL;

UPDATE wp_woocommerce_downloadable_product_permissions
SET
    access_expires = DATE_ADD(CURDATE(), @ar)
WHERE
    user_email = 'user@mail.com' AND
    product_id = 8 AND
    access_expires IS NULL

I suggest that SUM does not make sense in this context.

Wouldn't it be simpler to just do this?

UPDATE wp_woocommerce_downloadable_product_permissions
SET
    access_expires = GREATEST(access_expires, CURDATE()) + INTERVAL 30 DAY
WHERE
    user_email = 'user@mail.com' AND
    product_id = 8 AND
    access_expires IS NULL
Rick James
  • 135,179
  • 13
  • 127
  • 222