如何从SQLite中的表中删除多行

时间:2017-08-08 12:57:52

标签: sqlite subquery sql-delete

我有一个子查询:

SELECT INTER1.LID1 AS ILID1,INTER1.LID2 AS ILID2 FROM
(SELECT L1.ID1 AS LID1, L1.ID2 AS LID2 FROM Friend F1
INNER JOIN Likes L1
ON F1.ID1 = L1.ID1 AND F1.ID2 = L1.ID2) INTER1
LEFT JOIN Likes L2
ON (INTER1.LID1 = L2.ID2 AND INTER1.LID2 = L2.ID1)
WHERE (L2.ID1 IS NULL AND L2.ID2 IS NULL)

输出如下:

     ID1    ID2

    1641    1468
    1911    1247

现在我必须从表LIKES中删除这两行,其格式如下:

  ID1       ID2

 1689       1709
 1709       1689
 1782       1709
 1911       1247
 1247       1468
 1641       1468

我试图在SQLite中使用以下查询来完成此任务:

DELETE FROM Likes 
WHERE EXISTS 
(SELECT INTER1.LID1 AS ILID1,INTER1.LID2 AS ILID2 FROM
(SELECT L1.ID1 AS LID1, L1.ID2 AS LID2 FROM Friend F1
INNER JOIN Likes L1
ON F1.ID1 = L1.ID1 AND F1.ID2 = L1.ID2) INTER1
LEFT JOIN Likes L2
ON (INTER1.LID1 = L2.ID2 AND INTER1.LID2 = L2.ID1)
WHERE (L2.ID1 IS NULL AND L2.ID2 IS NULL));

但它没有按预期工作,它不会只删除那些行。

然后我尝试使用INNER JOIN来解决这个问题,但是与DELETE函数关联的INNER JOIN的功能并不在SQLite中。

我该怎样才能做到这一点。

请帮助

1 个答案:

答案 0 :(得分:1)

只需一次比较两个值:

DELETE FROM Likes
WHERE (ID1, ID2) IN (SELECT ... your original query ...);

Row values需要SQLite 3.15或更高版本。 如果您使用的是早期版本,则必须在单独的步骤中使用单列主键(rowid或您声明为INTEGER PRIMARY KEY的任何内容)查找要删除的行:

DELETE FROM Likes
WHERE rowid IN (SELECT Likes.rowid
                FROM Likes
                JOIN (SELECT ... your original query ...) AS IDs
                  ON Likes.ID1 = IDs.ILID1
                 AND Likes.ID2 = IDs.ILID2);