我有两张桌子
表1
\n
AND
表2
SNO RECEIVER USER1 USER2
1 133 44 45
2 144 66 77
3 155 77 33
必填: 从table1中删除table2中没有匹配条目的所有行
例如
RECEIVER USER
133 44
133 45
144 88
144 55
155 77
应该删除 因为table2上没有144 66行
155 33
我试过但它不起作用 DELETE FROM TABLE1 LEFT JOIN TABLE2 B ON(A.RECEIVER = B.RECEIVER和A.USER1 = B.USER)和B.USER为空;
答案 0 :(得分:1)
您也可以在DELETE语句中使用JOIN。以下语句连接(使用左连接!)两个表,从表2(WHERE ...)中选择没有相应记录的结果行,并从t1中删除相应的行:
DELETE t1
FROM t1 LEFT JOIN t2 ON (t1.RECEIVER = t2.RECEIVER AND t1.USER1 = t2.USER)
WHERE t2.RECEIVER IS NULL
请参阅manual以供参考,尤其是"多表删除"部分。
答案 1 :(得分:0)
为什么需要JOIN
来执行此操作,而不是使用SUB-QUERY
DELETE FROM table1
WHERE receiver NOT IN ( SELECT DISTINCT (receiver) FROM table2 )
AND user1 NOT IN ( SELECT DISTINCT (user) FROM table2 );
答案 2 :(得分:0)
Delete * from Table1
Where not exists (select 1 from Table2 where
RECEIVER = Table1.RECEIVER and (user = Table1.user1 or user = Table1.user2))
澄清不匹配的含义。您认为匹配什么?在我上面的回答中,我假设匹配意味着相同的接收器,user1或user2与Table2中的用户相同。如果不是这种情况,则可以修改查询。
答案 3 :(得分:0)
像:
SELECT t1.sno FROM table1 t1 LEFT JOIN table2 t2 ON t1.receiver = t2.receiver and 2.user = t1.user1 WHERE t2.receiver IS NULL;
以上查询通过接收者列和用户列连接这两个表,并仅选择那些没有匹配记录的记录(left join
,选择table1中的所有记录,而WHERE t2.receiver IS NULL
将仅选择那些没有匹配记录的记录表2中的匹配记录
现在你可以做到
delete from table1 where sno IN (__PASTE_ABOVE_QUERY__);