SQL - 如果相同的记录不在表Y中,则从表X中删除记录

时间:2016-05-11 20:07:46

标签: mysql sql sql-server

抱歉再次删除相同的记录,但是我找不到任何解决方案:(

我需要这样的东西:

如果从table1中选择3列值 是等于表2中的相同选择 从表2删除记录

这是我的答案:

DELETE FROM table2
INNER JOIN table1
ON table2.basketid = table1.basketid AND
table2.artid = table1.artid
WHERE table1.userid='007'

DELETE FROM table2
WHERE NOT EXISTS (
SELECT basketid, artid
FROM table1
)
AND userid ='007'

感谢您的帮助或任何帮助!

3 个答案:

答案 0 :(得分:2)

您可以在SQL Server中执行此操作

DELETE  t2
FROM    Table2 t2
WHERE   NOT EXISTS ( SELECT 1
                     FROM   Table1 t1
                     WHERE  t1.basketid = t2.basketid
                            AND t1.artid = t2.artid )
        AND t2.userid = '007'

注意select中的过滤器,用于比较Table2到Table1的值

如果userid也在Table2中,您可能还想将其添加到WHERE

DELETE  t2
FROM    Table2 t2
WHERE   NOT EXISTS ( SELECT 1
                     FROM   Table1 t1
                     WHERE  t1.userid = t2.userid
                            AND t1.basketid = t2.basketid
                            AND t1.artid = t2.artid )
        AND t2.userid = '007'

答案 1 :(得分:1)

你可能需要一个不在()

中的where()
DELETE FROM table2
WHERE (basketid, artid ) NOT IN (
       SELECT basketid, artid
       FROM table1
      )
AND userid ='007';

答案 2 :(得分:0)

.small {
  vertical-align: top;
}

试试上面的代码。