从SQLite3删除重复行

时间:2015-09-06 02:54:50

标签: sqlite

我有一个包含大约10,000行数据的SQLite3数据库。

架构是这样的:

id, stock_id, body, stock_created_at, symbol, updated_at, created_at

PK为id,没有FK

如果stock_id重复,您可以判断重复。

我有一个像我以前常用的MySQL查询,但它适用于MySQL,而不是SQLite:

DELETE FROM stocks WHERE id NOT IN
    (SELECT MAX(id) FROM table GROUP BY stock_id);

1 个答案:

答案 0 :(得分:2)

使用SQLite3(SQLite版本3.8.10.2 2015-05-20 18:17:19):

sqlite> create table test (id int, stock_id int, symbol text);
sqlite> insert into test values (1, 1, 'GOOG');
sqlite> insert into test values (2, 1, 'GOOGL');
sqlite> insert into test values (3, 2, 'AAPL');

sqlite> select * from test;
id          stock_id    symbol
----------  ----------  ----------
1           1           GOOG
2           1           GOOGL
3           2           AAPL

sqlite> delete from test 
   ...> where id in (
   ...>  select max(id) from test 
   ...>  group by stock_id 
   ...>  having count(*) > 1
   ...> );

sqlite> select * from test;
id          stock_id    symbol
----------  ----------  ----------
1           1           GOOG
3           2           AAPL

如果stock表是一个完全不同的表,那么相同的概念效果很好:

sqlite> create table stock (stock_id int);
sqlite> insert into stock values (1);
sqlite> insert into stock values (2);
sqlite> insert into stock values (3);
sqlite> delete from stock
   ...> where stock_id in (
   ...>   select max(id) from test
   ...>   group by stock_id
   ...>   having count(*) > 1
   ...> );
sqlite> select * from stock;
stock_id
----------
1
3

这种查询对您有用吗?如果没有,您使用的是什么SQLite版本,是否可以使用示例数据编辑问题?