使用非关联子查询查询下单数恰好为3的客户姓名(不使用JOIN)
数据表结构及示例数据
1. customer表
字段包含cust_id、cust_name,示例数据如下:
cust_id, cust_name 121 Acme Wholesalers 234 Griffen Electric 336 East Coast Marine Supplies 544 Sanford Automotive
2. customer_orders表
字段包含order_num、cust_id、order_date,示例数据如下:
order_num,cust_id,order_date 1 121 2019-01-15 2 234 2019-07-24 3 336 2020-05-02 4 121 2019-01-15 5 336 2020-03-19 6 234 2019-07-24 7 121 2019-01-15 8 336 2020-06-12
实现要求
- 仅使用非关联子查询实现,禁止使用JOIN语句
- 查询目标:下单数量恰好为3的客户姓名
注:你之前给出的关联子查询代码逻辑不成立,
GROUP_CONCAT返回的是拼接字符串,无法和cust_id正确匹配,也不符合非关联子查询的要求。
符合要求的SQL代码
SELECT cust_name FROM customer WHERE cust_id IN ( -- 非关联子查询,可独立运行不依赖外层查询字段 SELECT cust_id FROM customer_orders GROUP BY cust_id HAVING COUNT(order_num) = 3 );
查询结果
执行上述代码后,返回符合条件的客户姓名如下:
- Acme Wholesalers
- East Coast Marine Supplies
内容的提问来源于stack exchange,提问作者Md Tausif
相关产品推荐
相关产品推荐

