sqlite:使用连接表中的max()更新TableA

时间:2016-03-25 05:29:46

标签: sqlite

我被多年的PostgreSQL宠坏了,并且很难适应sqlite的有限update语法。我拼凑了一个工作查询,但我希望有人可能知道更好的方法。 (这看起来不是很漂亮,是sqlite的产品,指导我提供错误消息)。

情景:

我有一个标准的关联表设置:A,A2B,B

我想更新A中的每个记录,其中“最新”对应B(B通过A2B关联表连接,“最新”是B列上的max函数。)

-- works
UPDATE t_a
SET id_latest_b = (
    SELECT id_b FROM (
        SELECT t_b.id as id_b, 
               max(t_b.timestamp_event),
               t_a2b.id_a
               FROM t_b
               JOIN t_a2b
                   ON (t_b.id = t_a2b.id_b)
               GROUP BY t_a2b.id_a
    ) q_inner
    WHERE 
    t_a.id = q_inner.id_a
);

-- test data
CREATE TABLE t_b (id INT PRIMARY KEY, timestamp_event INT);
CREATE TABLE t_a (id INT PRIMARY KEY, id_latest_b INT REFERENCES t_b(id));
CREATE TABLE t_a2b (id_a REFERENCES t_a(id), id_b REFERENCES t_b(id), PRIMARY KEY (id_a, id_b));
INSERT INTO t_a VALUES (1, NULL);
INSERT INTO t_a VALUES (2, NULL);
INSERT INTO t_a VALUES (3, NULL);
INSERT INTO t_a VALUES (4, NULL);
INSERT INTO t_b VALUES (1, 10);
INSERT INTO t_b VALUES (2, 20);
INSERT INTO t_b VALUES (3, 30);
INSERT INTO t_a2b VALUES (1, 1);
INSERT INTO t_a2b VALUES (1, 2);
INSERT INTO t_a2b VALUES (2, 2);
INSERT INTO t_a2b VALUES (3, 1);
INSERT INTO t_a2b VALUES (3, 2);
INSERT INTO t_a2b VALUES (3, 3);
INSERT INTO t_a2b VALUES (4, 1);
INSERT INTO t_a2b VALUES (4, 4);

1 个答案:

答案 0 :(得分:1)

您可以使用ORDER BY获取具有最大值的行:

UPDATE t_a
SET id_latest_b = (SELECT t_b.id
                   FROM t_b
                   JOIN t_a2b ON t_b.id = t_a2b.id_b
                   WHERE t_a2b.id_a = t_a.id
                   ORDER BY t_b.timestamp_event DESC
                   LIMIT 1);