我有5张桌子。我想让表1中的特定用户不在table2,table3,table4和table5中。有人可以帮助我:))
table1(userid,discount)
table2(userid,discount)
table3(userid,discount)
table4(userid,discount)
table5(userid,discount)
答案 0 :(得分:0)
以下查询:
SELECT userid
FROM table1 AS t1
WHERE NOT EXISTS (
SELECT 1
FROM (
SELECT userid
FROM table2
UNION
SELECT userid
FROM table3
UNION
SELECT userid
FROM table4
UNION
SELECT userid
FROM table5) AS t2
WHERE t1.userid = t2.userid)
返回所有其他表格中不存在的table1
用户。
如果您还希望所有table2
用户都不在其他任何表中,那么您可以修改上述查询,以便从table2
返回用户并在这两个查询之间执行UNION
:
SELECT userid
FROM table1 AS t1
WHERE NOT EXISTS (
SELECT 1
FROM (
SELECT userid
FROM table2
UNION
SELECT userid
FROM table3
UNION
SELECT userid
FROM table4
UNION
SELECT userid
FROM table5) AS t2
WHERE t1.userid = t2.userid)
UNION ALL
SELECT userid
FROM table2 AS t1
WHERE NOT EXISTS (
SELECT 1
FROM (
SELECT userid
FROM table1
UNION
SELECT userid
FROM table3
UNION
SELECT userid
FROM table4
UNION
SELECT userid
FROM table5) AS t2
WHERE t1.userid = t2.userid)
可以轻松扩展上述内容,以便合并所有表格中的用户。但是,我不得不承认,它变得非常冗长!