2011-05-11 96 views
0

我正在处理一个查询,该查询正在连接多个表以进行深入分析,以获取订阅者投票次数超过一个区域的订阅者数量。MySQL选择行大于1的行

我被困在的问题是试图在查询中计算订阅者投票超过一个的计算。

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

任何想法?

+0

你能更清楚地解释你要找的是什么号码吗?如果子查询不能保证返回单个行,这将始终给出错误,因为它期望子查询中的字段名称。 – Mel 2011-05-11 20:16:54

回答

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行结果。

0

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

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

你要找的COUNT(*)是否与regions.name匹配?你必须连接内部查询。

+0

谢谢Flupps - 我为这个查询提供的标准是根据地区查找具有多个投票的订户数量。从上面的查询中可以看出,我在SQL中并不是非常强大,但我正在学习:D – dennismonsewicz 2011-05-11 20:19:07

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”

0

尝试将HAVING vote_count > 1子句放入子查询中。另外,请尝试自己的子查询来查看它的成果。