假如,我现在有两个表,(只是假设这个场景)
table_a 如下:
table_b 如下:
我现在需要对这两个表进行关联查询,把 stu_id 相同,stu_name 不同的记录找出来,可是这两个表中,实际 stu_id 相同,stu_name 不同的记录只有两条,那就是 stu_id = 555 和 stu_id = 666 的两条记录,其他都能对应得上,但是如果用关联查询的话,查询出来所有记录如下:
select a.stu_id stu_id, a.stu_name stu_name, b.stu_id stu_id_new, b.stu_name stu_name_new from table_a a join table_b b on a.stu_id = b.stu_id order by a.stu_id,a.stu_name;
全部都关联出来了,如果只要查找 stu_id 相同,stu_name 不同的,如下:
select a.stu_id stu_id, a.stu_name stu_name, b.stu_id stu_id_new, b.stu_name stu_name_new from table_a a join table_b b on a.stu_id = b.stu_id where a.stu_name <> b.stu_name order by a.stu_id,a.stu_name;
可是,这结果里面,我真正想要的只有下面画圈的那两条啊
遇到这种情况,我该如何查出我要的结果来???
你这应该少加了一些筛选条件。
select distinct * from table_a a inner join table_b b on a.tid = b.b_id and a.tname <> b.b_name
and tname not in(select b_name from table_b) ;
;
我写的查询,结果如上,如果我的回答对你有帮助,万望采纳。
这样写就可以了:
select a.* from table_a a inner join table_b b on a.stu_id = b.stu_id and a.stu_name <> b.stu_name order by a.stu_id,a.stu_name;
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632