请教关于 MYSQL 的 join 查询

2014-11-24 10:38:41 +08:00
 xia0chun

现有两个表
table1:
id, name
1, 张一
2, 张二
3, 张三
4, 张四
table2:
id, name
1, 张一
3, 张三
5, 张五

问题:需要查询出table1中不在table2中的记录,即
id, name
2, 张二
4, 张四

由于对数据库只是学了个皮毛,希望各位指点
ps:我现在可以查出table1中在table2中的记录,SQL如下
SELECT * FROM table1
right join table2
on table1.id = table2.id

再次表示感谢 :)

2759 次点击
所在节点    问与答
11 条回复
xia0chun
2014-11-24 10:51:24 +08:00
自己来回答吧,再加一个where条件就可以了
SELECT * FROM table1
left join table2
on table1.id = table2.id
where table2.id is NULL
fengchang
2014-11-24 11:12:44 +08:00
把right join改成inner join就行了
xia0chun
2014-11-24 11:20:05 +08:00
@fengchang 我想要查出table1中 不在 table2中的记录,要是用inner join应该是找出table1和table2中相同的记录吧?
Seans
2014-11-24 11:26:05 +08:00
select * from table1 where id not in(select id from table2);
feiyuanqiu
2014-11-24 12:24:14 +08:00
直接用1L的SQL就行了,后面的朋友们的回复都不太靠谱...
xia0chun
2014-11-24 12:56:37 +08:00
@Seans 嗯嗯真是难者不会 会者不难呀,感谢已发

@feiyuanqiu 谢谢指点,感谢已发
fengchang
2014-11-24 13:49:32 +08:00
@xia0chun sorry看错了,是1L那样
Raidal
2014-11-24 14:40:03 +08:00
刚刚正好用left join和where写了条查询差集的sql
coolzjy
2014-11-24 14:49:55 +08:00
为什么不用not in?
iyaozhen
2014-11-24 16:27:00 +08:00
4楼方法更简单除暴吧。
kenzi
2014-11-24 18:42:22 +08:00
我都用4楼的方法

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/148820

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX