列的默认值是否可以作为查询结果,只要查询该值,该值就会自动更新?
我有一个带有成员和取消表的数据库,我希望将members.NumberOfCancellations值自动填充为下面的伪查询的结果:
从取消的所有取消中选择所有取消。从今天起不到31天,其中cancellations.memberid等于$ phpvariable
我知道这可以用php和select / update脚本完成,但我希望phpmyadmin可能有这个功能吗?
______________________________________________________________
|memberid | firstname | lastname | numberofcancellations|
______________________________________________________________
|1 | john | doe | resultofquery(= 2) |
|2 | Dave | Smith | resultofquery (=1) |
______________________________________________________________
___________________________________
|id |memberid | date | time | group |
___________________________________
|1 |1 |2016-04-19 | 08:00 | 1 |
|2 |2 |2016-04-18 | 13:00 | 4 |
|3 |1 |2016-04-15 | 18:00 | 3 |
_______________________________________________
答案 0 :(得分:0)
如果您的members
表还没有取消计数列,请添加:
ALTER TABLE members ADD numberofcancellations int AFTER lastname;
现在,您可以使用取消计数更新members
:
UPDATE members t1 LEFT JOIN
(
SELECT memberid, COUNT(*) AS numberofcancellations
FROM cancellations
WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
GROUP BY memberid
) t2
ON t1.memberid = t2.memberid
SET t1.numberofcancellations = COALESCE(t2.numberofcancellations, 0)
您需要运行此查询一次以初始填充新列。如果您想更新单个成员,则可以在WHERE
语句中添加UPDATE
条件:
UPDATE members t1 LEFT JOIN
(
SELECT memberid, COUNT(*) AS numberofcancellations
FROM cancellations
WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
GROUP BY memberid
) t2
ON t1.memberid = t2.memberid
SET t1.numberofcancellations = COALESCE(t2.numberofcancellations, 0)
WHERE t1.memberid = 1 -- or whatever value you want