2012-10-29 16 views
1

我正在做一個mysql事件中的select,然後試圖用該選擇中的數據更新另一個表。但它似乎並沒有工作。在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

回答

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); 
+0

所以,如果我這樣做,我不需要在那裏使用select語句? – Norman

+0

不需要選擇語句,如果你這樣做 – SRIRAM

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更新每一行,我不知道這真的是你想要的。

+0

沒錯。該作者和帖子的每一行都需要更新。 – Norman