SQL每日一题(20230814)

  1. SQL每日一题(20230814)
    1. 题目
    2. 要求:用至少四种方法求解。
    3. 参考答案

SQL每日一题(20230814)

题目

有如下两张表G0227A(客户表)

Id Name
1 曹操
2 关于
3 刘备
4 张飞

G0227B(订单表)

Id CustomerId
1 3
2 1

查询G0227B表(订单表)中找出从来没有买过商品的用户。

预计结果如下:

Id Name
2 关于

要求:用至少四种方法求解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
create table G0814A  
(
Id int,
Name varchar(20)
)

insert into G0814A values (1,'曹操');
insert into G0814A values (2,'关羽');
insert into G0814A values (3,'刘备');
insert into G0814A values (4,'张飞');

create table G0814B(
Id int,
CustomerId int
)

insert into G0814B values (1,3);
insert into G0814B values (2,1);

参考答案

1
2
3
4
5
6
7
8
9
10
11
12
-- 方法一: 关联查询
SELECT a.* FROM G0814A aLEFT JOIN G0814B b ON b.customerid=a.idWHERE b.customerid IS NULL;

-- 方法二:不存在 not exists
select *from G0814A awhere not exists(select * from G0814B bwhere a.id = b.customerid;

-- 方法三:不包含 not in
selectfrom G0814A awhere a.id not inselect b.customerid from G0814B b);

-- 方法四: 差集
select * from G0814Awhere id inselect a.id from G0814A aexceptselect b.customerid from G0814B b
);

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 richffan@outlook.com

文章标题:SQL每日一题(20230814)

字数:238

本文作者:Rich Fan

发布时间:2023-08-01, 00:00:00

最后更新:2024-02-27, 08:17:39

原始链接:http://fanrich.github.io/2023/07/31/SQL/SQL%20daily%20question%20%2020230814/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。