SELECT * FROM 'income'; -- Returns all 309 rows.
SELECT * FROM 'income' WHERE businessday_revision = 0; -- 308 rows
SELECT * FROM 'income' WHERE businessday_revision = 1; -- 1 row
businessday表有:
id INTEGER,
revision INTEGER,
....
PRIMARY KEY(id, revision)
收入表有:
id -- integer primary key, quite unimportant I think
businessday_id -- FK
businessday_revision -- FK, when a day is edited, a new revision is created
外键如下所示:
FOREIGN KEY(businessday_id, businessday_revision) REFERENCES businessday(id, revision) ON DELETE CASCADE,
我想从每天的最新版本中选择收入。 哪一行应为308行。 但遗憾的是,我太密集了,无法弄明白。我发现我可以使用这个获得所有最新的businessday修订版:
SELECT id, MAX(revision)
FROM businessday
GROUP BY id;
我有什么办法可以用这些数据来选择我的收入吗?有点像:
-- Pseudo-code:
SELECT *
FROM income i
WHERE i.businessday_id = businessday.id THAT EXISTS IN
(SELECT id, MAX(revision)
FROM businessday
GROUP BY id);
我显然在这里没有任何线索,请指出正确的方向!
答案 0 :(得分:1)
如何使用join?
SELECT i.*
FROM income i
INNER JOIN
(
SELECT id, MAX(revision) revision
FROM businessday
GROUP BY id
) s ON i.businessday_id = s.id AND
i.businessday_revision = s.revision
答案 1 :(得分:1)
这应该有效:
SELECT i.*
FROM Income i
INNER JOIN (
SELECT id, MAX(revision) maxrevision
FROM businessDay
GROUP BY id
) t ON i.businessday_id = t.id AND i.businessday_revision = t.maxrevision