SQL每日一題(2020-07-01) ***

題目:

訂單中有多個商品,想要查詢訂單表(Orders)中同時包含有商品A、商品B、商品C等的所有訂單信息。
image

希望得到如下結(jié)果:
image

該如何寫這個查詢?

參考答案:

數(shù)據(jù)庫版本:Server version: 8.0.20 MySQL Community Server - GPL

建表語句

create table dailytest_20200701(
    order_id int,
    product varchar(20));

數(shù)據(jù)準(zhǔn)備

insert into dailytest_20200701 values (1001,'A'),(1001,'B'),(1001,'C'),(1001,'D'),(1002,'A');

查詢邏輯-方法1

select
       A.order_id
from (select order_id from dailytest_20200701 where product = 'A') A,
     (select order_id from dailytest_20200701 where product = 'B') B,
     (select order_id from dailytest_20200701 where product = 'C') C
where A.order_id = B.order_id
  and B.order_id = C.order_id;

查詢邏輯-方法2

select
    AA.order_id,
    AA.product
from dailytest_20200701 AA
where exists(select 1 from dailytest_20200701 A where A.order_id = AA.order_id and A.product = 'A')
and exists(select 1 from dailytest_20200701 B where B.order_id = AA.order_id and B.product = 'B')
and exists(select 1 from dailytest_20200701 C where C.order_id = AA.order_id and C.product = 'C')
and product in ('A','B','C');

查詢邏輯-方法3

select
       order_id
from dailytest_20200701
where product in ('A','B','C')
    group by order_id
    having count(distinct product) =3;

附:
題目來源:https://mp.weixin.qq.com/s/2yq6TjjGnKVaqg6o3AWJtA

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容