问个sql join table的问题

p
pineappletin
楼主 (北美华人网)
我几年没用忘记了…如果我有两个table,一个500,一个400,我要找出table 2里缺失的100项,应该怎么join?left join 后 where 怎么用?
马蹄莲
去问chatgpt
g
gokgs
NOT IN 加上一个 nested query 就行了吧?
key 这么几个,两个query 加excel 也行。

p
pineappletin
去问chatgpt
马蹄莲 发表于 2023-04-14 18:02

我问了,where 后面跟 table2.key is null,可是没结果
金银岛
Select * from table1 where key not in (select key from table2);
f
fridec2
https://stackoverflow.com/questions/2686254/how-to-select-all-records-from-one-table-that-do-not-exist-in-another-table
so it''s this:
SELECT t1.name FROM table1 t1 LEFT JOIN table2 t2 ON t2.name = t1.name WHERE t2.name IS NULL
H
Hesterhql
SELECT A.* FROM A LEFT JOIN B ON (A.C = B.C) WHERE B.C IS NULL
p
pineappletin
https://stackoverflow.com/questions/2686254/how-to-select-all-records-from-one-table-that-do-not-exist-in-another-table
so it''s this:
SELECT t1.name FROM table1 t1 LEFT JOIN table2 t2 ON t2.name = t1.name WHERE t2.name IS NULL
fridec2 发表于 2023-04-14 18:09

我用的就是这个,可结果只出来一行
d
dngdnhxqs
我也学过 但是目前也不记得怎么做了 不用确实就忘了
s
shoon_yee
我问了,where 后面跟 table2.key is null,可是没结果
pineappletin 发表于 2023-04-14 18:03

left join table2 或是用not in, 这个需要比较的column里没有null。
b
bplus
https://stackoverflow.com/questions/2686254/how-to-select-all-records-from-one-table-that-do-not-exist-in-another-table
so it''s this:
SELECT t1.name FROM table1 t1 LEFT JOIN table2 t2 ON t2.name = t1.name WHERE t2.name IS NULL
fridec2 发表于 2023-04-14 18:09

这个是正解 我一直用啊
p
pineappletin
谢啦谢啦,我调整了一下可以啦
f
fridec2
可以在这先试一下:找从没买过东西的 customer
https://www.w3schools.com/sql/trysql.asp?filename=trysql_asc
(1) SELECT t1.*  FROM customers t1 LEFT JOIN orders t2 ON t2.customerid = t1.customerid WHERE t2.customerid IS NULL;
(2) select * from orders where customerid = 6;
(3) select * from orders where customerid = 7;
看着是对的 😄
c
conundrum
我用的就是这个,可结果只出来一行
pineappletin 发表于 2023-04-14 18:12

所以你先要inner join test table A (500 records ) 是否和table B(400) 真有400个相同的记录,如果不是,A left join B return 1 record 当然可能。
y
yimiyangguang
用 not in 也可以
select * from table a where a.id not in (select id from table b)
j
jianliu67
用 not in 也可以
select * from table a where a.id not in (select id from table b)
yimiyangguang 发表于 2023-04-14 18:30

"Not In" will not work if there are nulls.
z
zhikantie
6楼和7楼是正解,用left join
H
Hesterhql
自己找个online sql 创建一些dummy data, 试一下就知道了。
B
Brandypurple
谢啦谢啦,我调整了一下可以啦
pineappletin 发表于 2023-04-14 18:22

怎么调整的?能不能发上来让大家学习一下。