V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
xia0chun
V2EX  ›  问与答

请教关于 MYSQL 的 join 查询

  •  
  •   xia0chun · 2014-11-24 10:38:41 +08:00 · 2760 次点击
    这是一个创建于 3444 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现有两个表
    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

    再次表示感谢 :)

    11 条回复    2014-11-24 18:42:22 +08:00
    xia0chun
        1
    xia0chun  
    OP
       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
        2
    fengchang  
       2014-11-24 11:12:44 +08:00
    把right join改成inner join就行了
    xia0chun
        3
    xia0chun  
    OP
       2014-11-24 11:20:05 +08:00
    @fengchang 我想要查出table1中 不在 table2中的记录,要是用inner join应该是找出table1和table2中相同的记录吧?
    Seans
        4
    Seans  
       2014-11-24 11:26:05 +08:00   ❤️ 1
    select * from table1 where id not in(select id from table2);
    feiyuanqiu
        5
    feiyuanqiu  
       2014-11-24 12:24:14 +08:00   ❤️ 1
    直接用1L的SQL就行了,后面的朋友们的回复都不太靠谱...
    xia0chun
        6
    xia0chun  
    OP
       2014-11-24 12:56:37 +08:00
    @Seans 嗯嗯真是难者不会 会者不难呀,感谢已发

    @feiyuanqiu 谢谢指点,感谢已发
    fengchang
        7
    fengchang  
       2014-11-24 13:49:32 +08:00
    @xia0chun sorry看错了,是1L那样
    Raidal
        8
    Raidal  
       2014-11-24 14:40:03 +08:00
    刚刚正好用left join和where写了条查询差集的sql
    coolzjy
        9
    coolzjy  
       2014-11-24 14:49:55 +08:00
    为什么不用not in?
    iyaozhen
        10
    iyaozhen  
       2014-11-24 16:27:00 +08:00
    4楼方法更简单除暴吧。
    kenzi
        11
    kenzi  
       2014-11-24 18:42:22 +08:00 via Android
    我都用4楼的方法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5168 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 1698ms · UTC 01:22 · PVG 09:22 · LAX 18:22 · JFK 21:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.