MySQL select rows that do not have matching column in other table

前端 未结 3 1582
南笙
南笙 2020-12-13 13:21

I can\'t seem to figure this out so far. I am trying to join two tables and only select the rows in table A that do not have a matching column in table B. For example, lets

3条回答
  •  生来不讨喜
    2020-12-13 13:30

    Try this SQL:

    SELECT users.username
    FROM  users
    LEFT JOIN sent ON sent.username = users.username
    WHERE sent.username IS NULL;
    

    The better way in my opinion would be:

    SELECT users.username
    FROM  users
    LEFT JOIN sent ON sent.id = users.id
    WHERE sent.id IS NULL;
    

    As both the id fields, would be indexed (primary key I would have thought) so this query would be better optimised than the first one I suggested.

    However you may find my first suggestion better for you, it depends on what your requirements are for your application.

提交回复
热议问题