How to retrieve non-matching results in mysql

后端 未结 1 701
南笙
南笙 2020-12-10 06:50

I\'m sure this is straight-forward, but how do I write a query in mysql that joins two tables and then returns only those records from the first table that don\'t match. I w

相关标签:
1条回答
  • 2020-12-10 07:37

    You can use a left outer join to accomplish this:

    select
        t1.tid
    from
        table1 t1
        left outer join table2 t2 on
            t1.tid = t2.tid
    where
        t2.tid is null
    

    What this does is it takes your first table (table1), joins it with your second table (table2), and fills in null for the table2 columns in any row in table1 that doesn't match a row in table2. Then, it filters that out by selecting only the table1 rows where no match could be found.

    Alternatively, you can also use not exists:

    select
        t1.tid
    from
        table1 t1
    where
        not exists (select 1 from table2 t2 where t2.tid = t1.tid)
    

    This performs a left semi join, and will essentially do the same thing that the left outer join does. Depending on your indexes, one may be faster than the other, but both are viable options. MySQL has some good documentation on optimizing the joins, so you should check that out..

    0 讨论(0)
提交回复
热议问题