我使用的是SQLite3(版本3.8.6),我在数据库中有一个事务列表。我想DELETE
有少于10个关联交易的ID的记录。
我可以用它来列出id及其计数值:
SELECT id,count(id) AS cnt FROM purchases GROUP BY id HAVING cnt < 10;
我尝试将此用于DELETE
条记录:
DELETE
FROM purchases
WHERE
id IN
(SELECT id,count(id) AS cnt FROM purchases GROUP BY id HAVING cnt < 10);
然而,这给了我一个错误:
Error: only a single result allowed for a SELECT that is part of an expression
有没有一种优雅的方法来实现这一目标?
答案 0 :(得分:1)
试试这个:
DELETE
FROM purchases
WHERE
id IN
(SELECT id FROM purchases GROUP BY id HAVING count(*) < 10);
答案 1 :(得分:1)
SQLite应该怎么做?
id in (select id, count(id) from ...)
IN
运算符需要列表,而不是行集。省略指定的count(id)
列并直接在count(*)
子句中使用having
:
id in (select id from purchases group by id having count(*) < 10)
答案 2 :(得分:1)
问题出现在id IN (SELECT id,count(id) AS cnt FROM purchases GROUP BY id HAVING cnt < 10);
您使用了SELECT id
和count(id)
,基本上它会返回2列结果。使用IN
关键字时,您需要:id IN '001', '002', '003'...
要解决您的问题,您需要重新排列语法:
DELETE
FROM purchases
WHERE
id IN
(SELECT id FROM purchases GROUP BY id HAVING count(id) < 10);