【问题标题】:MySQL select where row is greater than oneMySQL选择其中行大于一
【发布时间】:2011-05-11 20:06:27
【问题描述】:

我正在处理一个查询,该查询将连接多个表以深入了解按订阅者拥有多于一票的地区投票的订阅者数量。

我遇到的问题是试图在查询中写出计算订阅者投票多于一个的位置。

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的错误

有什么想法吗?

【问题讨论】:

  • 您能否更清楚地解释您要查找的号码?如果子查询不能保证返回单行,这总是会出错,因为它需要来自子查询的字段名。

标签: mysql mysql-error-1242


【解决方案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”

【讨论】:

    【解决方案2】:

    如果您的子查询:

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

    【讨论】:

      【解决方案3】:

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

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

      您要查找与 region.name 匹配的 COUNT(*) 是什么?您必须将内部查询连接到它。

      【讨论】:

      • 感谢 Flupps - 为我提供此查询的标准是按地区查找拥有多于一票的订阅者数量。正如您可能从我上面的查询中看出的那样,我的 SQL 不是特别强,但我正在学习:D
      【解决方案4】:

      尝试将HAVING vote_count &gt; 1 子句放在子查询中。此外,请自行尝试子查询以查看其产生的结果。

      【讨论】:

        猜你喜欢
        • 2013-01-23
        • 1970-01-01
        • 1970-01-01
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        • 2018-06-15
        • 2011-11-23
        • 1970-01-01
        相关资源
        最近更新 更多