簡體   English   中英

MySQL選擇行大於一的地方

[英]MySQL select where row is greater than one

我正在處理一個查詢,該查詢將聯接多個表以進行向下鑽取,以獲取按用戶擁有一個以上投票權的地區進行投票的訂戶數量。

我遇到的問題是試圖寫在查詢中,以計算訂戶投票超過一個的地方。

SELECT COUNT(*), regions.name, 
(SELECT COUNT(*) FROM votes 
LEFT JOIN profiles on votes.subscriber_id = profiles.subscriber_id 
LEFT JOIN countries on profiles.country_id = countries.id 
WHERE countries.region_id = regions.id GROUP BY votes.subscriber_id) as vote_count 
FROM subscribers
LEFT JOIN profiles on subscribers.id = profiles.subscriber_id
LEFT JOIN countries on profiles.country_id = countries.id
LEFT JOIN regions on countries.region_id = regions.id 
LEFT JOIN votes on subscribers.id = votes.subscriber_id
WHERE subscribers.created_at < '2011-04-22 00:00:00'
GROUP BY regions.id
HAVING vote_count > 1;

與上面的查詢,我得到的錯誤, Subquery returns more than 1 row

有任何想法嗎?

這部分

SELECT COUNT(*) FROM votes 
LEFT JOIN profiles on votes.subscriber_id = profiles.subscriber_id 
LEFT JOIN countries on profiles.country_id = countries.id 
WHERE countries.region_id = regions.id GROUP BY votes.subscriber_id

返回多個結果。 嘗試刪除應該能夠解決問題的“ GROUP BY選民.subscriber_id”

如果您的子查詢:

(SELECT COUNT(*) FROM votes 
LEFT JOIN profiles on votes.subscriber_id = profiles.subscriber_id 
LEFT JOIN countries on profiles.country_id = countries.id 
WHERE countries.region_id = regions.id GROUP BY votes.subscriber_id)

返回多於1行的行,則將出錯,因為它試圖將行的集合放入值vote_count 您可以通過添加HAVING子句來保證查詢只有1行結果來解決此問題。

由於您將子查詢放置在查詢的SELECT部分​​中,因此只需要一個返回值(因為結果集是二維的)。

您必須在內部查詢的WHERE子句中添加與外部查詢的匹配項,以確保僅一行匹配。

您要尋找的與region.name匹配的COUNT(*)是什么? 您必須將內部查詢與此連接起來。

嘗試在子查詢中放入HAVING vote_count > 1子句。 另外,單獨嘗試子查詢以查看其產生的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM