[英]MySQL query to update list counts
I have a MySQL problem which I'm struggling to solve. 我有一个MySQL问题,正在努力解决。
I have two tables. 我有两张桌子。 The first is a table of many thousands of garden items each with a groupid, with many items falling into any given group id. 第一个是一个表格,其中包含成千上万个带有项id的花园项目,其中许多项属于任何给定的组id。 The second table is a summary table, simply listing the groupids and the count of items in each. 第二个表是一个汇总表,仅列出了组标识和每个条目中的项数。
I need a query that will regularly update this second table o be run as part of a batch process overnight. 我需要一个查询,该查询将定期更新第二个表,以便在一夜之间作为批处理的一部分运行。
So far I have got this far - the first query selects the groups and counts in the first table and next to them what the new counts should be - I am not sure how to complete it: 到目前为止,我已经了解了这一点-第一个查询选择了第一个表中的组和计数,然后在它们旁边显示了新的计数-我不确定如何完成它:
SELECT l.listid,l.subscribecount,count(ls.listid)
FROM `lists` as l,`list_items` as ls
where l.listid=ls.listid
group by listid;
update lists
left join list_items on
lists.listid = list_items.listid
set
lists.subscribecount = count(list_items.listid);
Any help would be appreciated as I am pretty new to mysql. 任何帮助将不胜感激,因为我是mysql的新手。
You could use the update-join syntax: 您可以使用update-join语法:
UPDATE lists l
JOIN (SELECT listid, COUNT(*) AS cnt
FROM list_items
GROUP BY listid) li ON l.listid = li.listid
SET l.subscribecount = cnt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.