mysql - 修复 "Subquery returns more than 1 row"错误

标签 mysql

当只有一种类型的分组响应时,我有一个查询准确返回我想要的内容。当有多个时,我收到“子查询返回超过 1 行”错误。

我尝试了多种构造查询的方法,包括使用“in”,但没有任何效果。

SELECT 
    (
    SELECT substring(postcode, 1, locate (' ', postcode) - 1)
    FROM user_locations AS ul
    JOIN users AS u ON u.id = ul.user_id
    WHERE u.membertype = "customer"
    ) AS postcode,
    (
    SELECT count(u.membertype)
    FROM users AS u
    JOIN user_locations AS ul ON u.id = ul.user_id
    WHERE u.membertype = "cook"
    GROUP BY ul.postcode

    ) AS cook,
    (
    SELECT count(u.membertype)
    FROM users AS u
    JOIN user_locations AS ul ON u.id = ul.user_id
    WHERE u.membertype = "customer"
    GROUP BY ul.postcode
    ) AS customer

我希望看到多个邮政编码

Postcode | Cooks | Customers
G83      | 12    | 34 
G84      | 19    | 76
G85      | 10    | 50

最佳答案

您可以使用表达式 u.membertype=xxx 在单个查询中执行此操作,如果 true 则为 1,否则为 0。

SELECT ul.postcode AS "Postcode",
       SUM(u.membertype="cook") as "Cooks"
       SUM(u.membertype="customer") as "Customers"
FROM users AS u
JOIN user_locations AS ul ON u.id = ul.user_id
GROUP BY ul.postcode

如果成员类型超过两种,可以添加WHERE u.membertype IN ("cook","customer")

关于mysql - 修复 "Subquery returns more than 1 row"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54525544/

相关文章:

php - MySQL User_ID - 需要帮助

php - 删除 php mysql 中的引号

mysql - 如何在不丢失全文索引的情况下连接表?

c# - WPF MVVM 组合框 SelectionChanged/SelectedItem

javascript - Node.js 中的 Mysql select 子句

类似sql操作符rails上的Mysql错误

php - 使用一个 PHP 在 MySQL 中插入多条记录

MySQL-PHP 从一列连接更多值

mysql - 限制mysql中查询数据

iphone - 将移动 (iPhone) 应用程序与网络应用程序同步