在SQL中查找多个表中的普通用户

时间:2015-10-26 07:06:53

标签: mysql sql

我有5张桌子。

我希望表1,表2和表3中的普通用户不在表4和表5中。

有人可以帮助我:)

表格

table1(userid,discount)

table2(userid,discount)

table3(userid,discount)

table4(userid,discount)

table5(userid,discount)

4 个答案:

答案 0 :(得分:3)

一种方法是,在表行上左连接省略:

select *
from   table1 a
join   table2 b on (a.userid = b.userid)
join   table3 c on (a.userid = c.userid)
left join table4 d on (a.userid = d.userid)
left join table5 e on (a.userid = e.userid)
where d.userid is null and e.userid is null;

答案 1 :(得分:0)

让表1,表2,表3的用户很容易 - 只需进行内连接即可。要获得不在表4或表5中的所有用户,您可以在where子句中的这些表中测试它们不存在。

select *
from table1
  join table2 on table1.userid = table2.userid
  join table3 on table1.userid = table3.userid
where
  not exists (select * from table4 where table4.userid = table1.userid)
  and not exists (select * from table5 where table5.userid = table1.userid)

答案 2 :(得分:0)

SELECT *
FROM   tableA a
JOIN   tableB b ON (a.userid = b.userid)
JOIN   tableC c ON (a.userid = c.userid)
LEFT JOIN tableD d ON (a.userid = d.userid)
LEFT JOIN tableE e ON (a.userid = e.userid)
WHERE d.userid IS NULL and e.userid IS NULL;

答案 3 :(得分:0)

尝试此查询

SELECT t1.userid, t2.userid, t2.userid, t4.userid, t5.userid
 FROM table1 t1
 LEFT JOIN table2 t2 ON (t2.userid = t1.userid)
 LEFT JOIN table3 t3 ON (t3.userid = t1.userid)
 LEFT JOIN table4 t4 ON (t4.userid = t1.userid)
 LEFT JOIN table5 t5 ON (t5.userid = t1.userid)
GROUP BY t1.userid
HAVING t1.userid IS NOT NULL 
     AND t2.userid IS NOT NULL
     AND t3.userid IS NOT NULL
     AND t4.userid IS NULL
     AND t5.userid IS NULL