2012-11-07 31 views
1

我想在mysql中編寫一個循環,以便一個查詢的結果通知第二個。這是我當前的查詢集:計算mysql循環查詢結果的數量

select @post_date := from_unixtime(post_date) 
from posts 
where post_date > unix_timestamp('2012-10-20') and nsfw=1; 

select @countofpost := count(@post_date); 

while @countofpost > 0 DO 

    select count(*) 
    from live_sharedata.users 
    where joined between @post_date and (@post_date + 21600) and joined_site_id="RS"; 

    set @countofpost = @countofpost -1; 

end while; 

我收到的錯誤是[錯誤] 1064-您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'while @countofpost> 0 DO附近使用正確的語法。

任何想法將不勝感激。

+0

我在看http://dev.mysql.com/doc/refman/5.1/en/while.html,它說這是做一個mysql while while循環的方式。我正在運行5.1.7。 –

回答

0

兩件事情:

  1. 運行SELECT @post_date; - 它告訴你正確的信息? MySQL中的變量不能包含數組或多個項目。如果您需要變量來保存多個對象,則需要使用CURSOR。您可以將它重寫爲SET @countofpost = FOUND_ROWS();FOUND_ROWS()返回在沒有LIMIT子句時將返回的行數,因此不需要在行集中運行COUNT()命令。

我相信,您需要使用光標重新編寫查詢,因爲(我認爲)您期望第一個SELECT @post_date := from_unixtime(post_date) ...查詢返回多個對象。請參閱Reference Manual's Cursor section瞭解更多信息。