【问题标题】:Correlated Subquery to determine Customer Records确定客户记录的相关子查询
【发布时间】:2020-04-20 21:28:58
【问题描述】:

我有两张表,customer 和 customer_order

客户

cust_id, cust_name
121 Acme 批发商
234 格里芬电气
336 东海岸海洋用品
544桑福德汽车

Customer_Orders

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

我需要编写一个查询来返回恰好下了 3 个订单的客户的姓名。我不能只返回一次相同的客户名称,我必须对 customer_order 表使用相关子查询。

到目前为止,我有以下内容,它返回了所有四个客户。

选择 c.cust_name
来自客户 c
存在于哪里
(选择计数(*)
来自customer_order co
其中 c.cust_id = co.cust_id);

我需要添加 = 3 限定符,但不确定在哪里。

【问题讨论】:

  • 请尝试该代码 select c.cust_name from customer c where cust_id IN (SELECT GROUP_CONACT(cust_id) FROM customer_order )
  • 我运行了查询但没有结果。
  • 请运行该代码 SELECT GROUP_CONACT(cust_id) FROM customer_order
  • 我得到以下信息:121,234,336,121,336,234,121,336
  • 请运行该代码 select c.cust_name from customer c where cust_id IN (121,234,336,121,336,234,121,336 )

标签: mysql sql correlated-subquery


【解决方案1】:

试试这个:

select c.cust_name, count(co.id) as num_orders
from customer c join customer_order co on c.cust_id = co.cust_id
group by c.cust_name
having  num_orders = 3;

我假设 cust_name 是唯一的,否则您必须按 cust_id 分组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多