在Mysql事件中进行选择和更新

时间:2012-10-29 04:46:20

标签: mysql sql

我在mysql事件中进行选择,然后尝试使用该选择中的数据更新另一个表。但它似乎没有起作用。

我在做:

BEGIN
select read_pub_id, read_artc_id, count(read_artc_id) as times_read from reads_t GROUP BY read_pub_id, read_artc_id;
update reads_totals set read_total = times_read where pub_id = read_pub_id and artc_id = read_artc_id;
update reads_totals set ts=now(); /*This is for testing*/
END

只有ts才会更新。这意味着事件正在发挥作用。

这里是否有一个while循环,以及如何添加?什么是正确的方法呢?

我之前有关此问题的问题是:

https://stackoverflow.com/questions/13110393/doing-a-count-along-with-distinct-to-check-number-of-times-a-post-was-read

2 个答案:

答案 0 :(得分:1)

你的意思是:

UPDATE reads_totals T
SET read_total = (SELECT count(read_artc_id) 
                  FROM reads_t R 
                  WHERE R.read_pub_id = T.pub_id 
                  AND R.read_artc_id = T.artc_id);

此查询会更新reads_totals中的每一行,我不确定这是否真的是你想要的。

答案 1 :(得分:1)

 select read_pub_id, read_artc_id, count(read_artc_id) as times_read from reads_t 
 GROUP BY read_pub_id, read_artc_id;
 update reads_totals
 set read_total = (select count(read_artc_id) from reads_t rt 
 where pub_id = rt.read_pub_id 
 and artc_id = rt.read_artc_id);