gpt4 book ai didi

mysql - SQL在子查询中检索过滤值

转载 作者:行者123 更新时间:2023-11-29 21:16:24 25 4
gpt4 key购买 nike

在此 cust_id 中是一个外键,ords 返回每个客户的订单数量

SELECT cust_name, (
SELECT COUNT(*)
FROM Orders
WHERE Orders.cust_id = Customers.cust_id
) AS ords
FROM Customers

输出是正确的,但我想过滤它以仅检索订单数量少于给定数量的客户,我不知道如何过滤子查询ords,我尝试了 WHERE ords < 2代码末尾,但它不起作用,我尝试在 cust_id 比较后添加 AND COUNT(*)<2 但它不起作用。我正在使用MySQL

最佳答案

使用 HAVING 子句(并使用联接而不是子查询)......

SELECT Customers.cust_id, Customers.cust_name, COUNT(*) ords
FROM Orders, Customers
WHERE Orders.cust_id = Customers.cust_id
GROUP BY 1,2
HAVING COUNT(*)<2

如果您想包含零阶的人员,请将连接更改为外部连接。

关于mysql - SQL在子查询中检索过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35904935/

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