【问题标题】:SQL - Finding Orders with only specific itemsSQL - 查找仅包含特定项目的订单
【发布时间】:2021-06-09 14:24:21
【问题描述】:

我想查找包含一种或多种产品的订单:A、B、C。

预期结果是:

order_id
101              (explanation: product A, B, C)
103              (explanation: product A)
106              (explanation: product A, B)
107              (explanation: product B)

订单

id deleted_at
101 null
102 null
103 null
104 null
105 5-5-2021
106 null
107 null

Order_items

id order_id product
1 101 A
2 101 A
3 101 B
4 101 C
5 102 A
6 102 D
7 103 A
8 104 D
9 105 D
10 105 B
11 106 A
12 106 B
13 107 B
14 107 B
15 107 B

我试过这样写代码,但它仍然包含其他不相关的命令。

select Orders.id
from Orders left join Order_items on Orders.id=Order_items.order_id
where Orders.deleted_at is null
group by Orders.id
having count(distinct(case 
when Order_items.product=A then 1
when Order_items.product=B then 1
when Order_items.product=C then 1 end)) between 1 and 3;

【问题讨论】:

    标签: mysql sql combinations calculation


    【解决方案1】:

    您可以计算不是 A、B 或 C 的产品,并确保它们都不在顺序中:

    select o.id
    from Orders o join
         Order_items oi
         on o.id = oi.order_id
    where o.deleted_at is null
    group by o.id
    having sum( oi.product not in ('A', 'B', 'C') ) = 0;
    

    请注意,这使用 MySQL 方便的简写来计算布尔匹配。

    【讨论】:

    • 谢谢!有用!!!!但我对此还有一个问题。我如何按产品展示它?预期结果是产品销售 A 3 B 3 C 1
    • @uyeahu 。 . .这不是你在这里问的问题。如果您有其他问题,请提出问题。
    【解决方案2】:

    只需检查它们是否存在,不需要连接。

    SELECT
        id
    FROM
        orders o
    WHERE
        EXISTS (
            SELECT
                NULL
            FROM
                order_items oi
            WHERE
                oi.order_id = o.id
                AND oi.product IN (
                    'A',
                    'B',
                    'C'
                )
        )
    

    【讨论】:

    • 谢谢!有用!!!!但我对此还有一个问题。我如何按产品展示它?预期结果是产品销售 A 3 B 3 C 1
    • 您能否编辑您的问题以显示您的预期输出以及它与原始问题的不同之处?对新要求不是很清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2012-12-26
    相关资源
    最近更新 更多