SQLite:如何计算表中每个ROWID的引用,然后插入计数

时间:2010-07-02 04:41:27

标签: sql sqlite

我需要一些帮助来编写SQL语句。我在SQLite数据库中有两个表:

CREATE TABLE users (
  user_id INTEGER PRIMARY KEY,
  item_id INTEGER
);

CREATE TABLE items (
  item_id INTEGER PRIMARY KEY,
  ref_count INTEGER
);

我正在寻找一个类似于以下伪代码的SQLite语句:

for each row in items
    items[ row ].ref_count = SELECT COUNT(users.item_id) 
                               FROM users 
                              WHERE users.item_id=row;

1 个答案:

答案 0 :(得分:1)

您似乎可以使用REPLACE命令,如下所示:

REPLACE INTO  items (item_id, ref_count)
SELECT        item_id, COUNT(*) AS ref_count
FROM          users
GROUP BY      item_id;

测试用例:

INSERT INTO users VALUES (1, 1);
INSERT INTO users VALUES (2, 1);
INSERT INTO users VALUES (3, 1);
INSERT INTO users VALUES (4, 2);
INSERT INTO users VALUES (5, 2);
INSERT INTO users VALUES (6, 3);

运行REPLACE查询后的结果:

SELECT * FROM items;

item_id       ref_co
------------  ------
1             3     
2             2     
3             1      

添加一些其他项目:

INSERT INTO users VALUES (7, 1);
INSERT INTO users VALUES (8, 4);
INSERT INTO users VALUES (9, 4);

重新运行REPLACE查询后:

SELECT * FROM items;

item_id       ref_co
------------  ------
1             4     
2             2     
3             1     
4             2