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

天大地大妈咪最大 提交于 2019-11-30 11:20:05

问题


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 assume we have a users table and a sent table.

users table has the following columns: id, username
sent table has the following columns: id, username

I want to select all rows from users where username does not exist in sent table. So, if tom is in users and in sent he will not be selected. If he is in users but not in sent he will be selected. I tried this but it didn't work at all:

SELECT pooltest.name,senttest.sentname 
FROM pooltest,senttest 
WHERE pooltest.name != senttest.sentname

回答1:


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.




回答2:


Typically, you would use NOT EXISTS for this type of query

SELECT p.Name
FROM   pooltest p
WHERE  NOT EXISTS (SELECT s.Name
                   FROM   senttest s
                   WHERE  s.Name = p.Name)

An alternative would be to use a LEFT OUTER JOIN and check for NULL

SELECT p.Name
FROM   pooltest p
       LEFT OUTER JOIN senttest s ON s.Name = p.Name
WHERE  s.Name IS NULL

Note that the implicit join syntax you are using is considered obsolete and should be replaced with an explicit join.




回答3:


May be this one can help you ....

I had also the same problem but Solved using this this query

INSERT INTO tbl1 (id,name) SELECT id,name from tbl2 where (name) not in(select name from tbl1);

hope this one will solve your problem



来源:https://stackoverflow.com/questions/10968767/mysql-select-rows-that-do-not-have-matching-column-in-other-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!