0

您需要了解的有关架构和数据的信息:

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

工作日表有:

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 行。 但可悲的是,我太密集了,无法弄清楚。我发现我可以使用以下方法获得所有最新的工作日修订:

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);

我显然对此一无所知,请指出正确的方向!

4

2 回答 2

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
于 2013-06-28T02:55:37.927 回答
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
于 2013-06-28T02:55:43.860 回答