如何在SQLITE中使用Row_Number()删除一个特定的行?

um6iljoc  于 2023-03-19  发布在  SQLite
关注(0)|答案(2)|浏览(204)

我是SQL的新手,我希望能够执行查询来删除表中没有PK的特定行(非重复行)(用于研究/学习目的)。

|--------------------------Users---------------------------|
|-ID (PK, AutoIncrement, NN)-|-username(NN)-|-password(NN)-|
|-            1             -|-    abc     -|-     abc    -|
|-            2             -|-    123     -|-     123    -|
|-            3             -|-    qwe     -|-     qwe    -|
|----------------------------------------------------------|
|---------------------------SavedCarts----------------------------|
|- user(FK references Users("id")) -|- cart_content VARCHAR(255) -|
|-               1                 -|- egg,3,milk,4,bread,4      -|
|-               1                 -|- egg,3,milk,1              -|
|-               1                 -|- egg,3,milk,2,cookie,6     -|
|-               2                 -|- egg,3,milk,3              -|
|-               2                 -|- egg,6,milk,5,cereal,5     -|
|-----------------------------------------------------------------|

在本例中,“SavedCarts”表保存了登录用户的购物车内容。例如,我想从SavedCarts表中删除“row number 3”。
我能够使用以下脚本执行SELECT查询,返回用户1的所有cart_content:

SELECT ROW_NUMBER() OVER ( PARTITION BY user) RowNum, 
cart_content 
FROM SavedCarts 
WHERE user = 1;

我能够使用以下脚本执行SELECT查询,该查询仅返回用户1的特定cart_content:

SELECT * 
FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY user) RowNum FROM SavedCarts ) 
WHERE user = 1 AND RowNum = 3;

但是,在实现删除表中特定行的相同逻辑时,我无法使其工作(也许我在删除脚本中做错了什么)。我知道在表中只包含一个PK要简单得多,但这是为了学习。我一直在网上搜索,我只能找到使用ROW_NUMBER的其他人()来删除重复的行(我也尝试过使用他们的逻辑)。谁能告诉我是否可以使用ROW_NUMBER()删除一行,并建议我如何实现它?
谢谢大家!
我试过:

DELETE FROM SavedCarts 
WHERE (user) IN (
   SELECT user FROM (
      SELECT user, ROW_NUMBER() OVER(PARTITION BY user) AS rownum 
      FROM SavedCarts
   ) 
   WHERE user = ? AND rownum = ?
);
DELETE FROM SavedCarts 
WHERE user IN (
   SELECT * FROM (
      SELECT *, ROW_NUMBER() OVER(PARTITION BY user) AS rownum 
      FROM SavedCarts
   ) 
   WHERE rownum = ?
);
(this deletes everything of user 1);
DELETE FROM SavedCarts 
WHERE user = ? AND ROW_NUMBER() OVER(PARTITION BY user) = ?;

编辑:我已经尝试CTE,但我得到这个错误:[SQLITE_ERROR] SQL错误或缺少数据库(无此类表:**这是因为SQLITE不支持CTE吗?**有没有办法在没有CTE的情况下实现这一点?

6fe3ivhb

6fe3ivhb1#

例如,我想从SavedCarts表中删除“行号3”。
您可以按以下方式执行此操作:

WITH cte AS (
  SELECT rowid, ROW_NUMBER() OVER (PARTITION BY user ORDER BY rowid) AS RowNum
  FROM SavedCarts
  WHERE user = 1
)
DELETE FROM SavedCarts
WHERE rowid IN (SELECT rowid FROM cte WHERE RowNum = 3);
igsr9ssn

igsr9ssn2#

WITH CTE AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY user) AS RowNum
  FROM SavedCarts
)
DELETE FROM CTE
WHERE user = 1 AND RowNum = 3;
  • CTE创建一个具有附加RowNum列的临时结果集,该列是每个用户的行号
  • 然后通过在DELETE语句的WHERE子句中指定user和RowNum值来删除所需的行

相关问题