gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:20:38 27 4
gpt4 key购买 nike

当只有一种类型的分组响应时,我有一个查询准确返回我想要的内容。当有多个时,我收到“子查询返回超过 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com