MySQL选择行大于1的位置

时间:2011-05-11 20:06:28

标签: mysql mysql-error-1242

我正在处理一个查询,该查询正在加入多个表格以向下钻取,以获得按订阅者投票多次的地区投票的订阅者数量。

我所困扰的问题是试图在计算用户投票不止一个的位置时查询。

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

有什么想法吗?

4 个答案:

答案 0 :(得分:1)

部分

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 votes.subscriber_id”

答案 1 :(得分:0)

如果您的子查询:

(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行结果来解决这个问题。

答案 2 :(得分:0)

由于您将子查询放在查询的SELECT部分​​中,因此只需要一个返回值(因为结果集是二维的)。

您必须在内部查询的WHERE子句中添加一个与外部查询匹配的位置,以确保只有一行匹配。

你正在寻找哪些COUNT(*)匹配regions.name?您必须将内部查询连接到该。

答案 3 :(得分:0)

尝试将HAVING vote_count > 1子句放在子查询中。此外,尝试自己的子查询,看看它产生了什么。