开发者

What would MYSQL look for getting data from 2 tables if they do not match to table 3?

Lately i been doing some work on my MySql class in php and as result of optimizing some parts of my code i would like to narrow some function count down. I am really having hard time to work with 3 or more tables because it's getting really confusing there. I don't have a lot experience working with MySql or any other database, but i know t开发者_开发知识库he basics and little bit more.

And for the problem i can't figure our how to make statement like so:

[table1 - users.email] AND [table2 - subscribers.email] NOT IN [table3 - check.email]

In words that would look like "Get me all unique user emails from [table1] and [table2] that are not in [table3] and put them in 1 list "

By 1 list i mean the same as this statement does it

SELECT u.email FROM users AS u UNION SELECT s.email FROM subscribers AS s

Thanks in advance, please say if you need any more information.


You left join the 3rd table and then do "where t3.field IS NULL"

example:

SELECT u.email FROM users AS u 
LEFT JOIN table3 t3 ON u.email = t3.email
WHERE t3.email IS NULL
UNION 
SELECT s.email FROM subscribers AS s
LEFT JOIN table3 t3 ON s.email = t3.email
WHERE t3.email IS NULL

You need to make this distinct as well to get unique results.


How about this:

SELECT Email From 
(
   Select Email From Table1
   UNION ALL 
   SELECT Email From Table2
) AS T
WHERE T.Email NOT IN (SELECT Email From Table3)

The performance here is NOT as great as a JOIN solution.


Maybe something like this

  select *
   from users
   left join subscribers on users.email = subscribers.email
   left join check on check.email = users.email
   where table3.email = null

Note, this is different than some of the other answers -- it assumes that subscribers is a related table. The way your answer is worded (and other answers) assume subscribers and users are mutually exclusive.


Depending on your DB, something like this should work...


select u1.email 
from users u1 
where u1.email not in (select table3.email from table3) 
union
select s1.email 
from subscribers s1 
where s1.email not in (select table3.email from table3) 

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜