简体   繁体   English

MySQL选择行大于一的地方

[英]MySQL select where row is greater than one

I am working on a query that is joining multiple tables to drill down to get the number of subscribers who voted by region where subscribers have more than one vote. 我正在处理一个查询,该查询将联接多个表以进行向下钻取,以获取按用户拥有一个以上投票权的地区进行投票的订户数量。

The issue I am stuck at is trying to write in the query of figuring out the calculation of where subscribers voted more 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;

With the above query I am getting the error of, Subquery returns more than 1 row 与上面的查询,我得到的错误, Subquery returns more than 1 row

Any ideas? 有任何想法吗?

The section 这部分

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

is returning more than one result. 返回多个结果。 Try removing the "GROUP BY votes.subscriber_id" which should solve the problem 尝试删除应该能够解决问题的“ GROUP BY选民.subscriber_id”

if your subquery: 如果您的子查询:

(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)

returns more than 1 row, then it will error, because it's trying to put a collection of rows into the value vote_count . 返回多于1行的行,则将出错,因为它试图将行的集合放入值vote_count You could solve this by guaranteeing the query has only 1 row result by adding a HAVING clause. 您可以通过添加HAVING子句来保证查询只有1行结果来解决此问题。

Since you place the sub query in the SELECT part of the query, only one return value is expected (since result sets are two dimensional). 由于您将子查询放置在查询的SELECT部分​​中,因此只需要一个返回值(因为结果集是二维的)。

You have to add somewhere in the inner query's WHERE clause a match to the outer query to make sure only one row matches. 您必须在内部查询的WHERE子句中添加与外部查询的匹配项,以确保仅一行匹配。

What COUNT(*) is it you're looking for that matches regions.name? 您要寻找的与region.name匹配的COUNT(*)是什么? You have to connect the inner query to that. 您必须将内部查询与此连接起来。

Try putting the HAVING vote_count > 1 clause in the subquery. 尝试在子查询中放入HAVING vote_count > 1子句。 Also, try the subquery on its own to see what it's yielding. 另外,单独尝试子查询以查看其产生的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM