这会产生语法错误:
SELECT id, name, body, DISTINCT(sequence) FROM `contents`
WHERE (`contents`.section_id = 74)
ORDER BY sequence ASC, revision DESC
Hokay,所以,在我的表中,我想根据序列号选择具有最新版本号的记录。
所以...我可以有这样的记录
seq | rev
0 | 2
0 | 1
0 | 0
1 | 1
1 | 0
2 | 3
2 | 1
2 | 0
我正在尝试编写一个查询来返回以下内容
seq | rev
0 | 2
1 | 1
2 | 3
注意:为了清洁问题,我遗漏了所有其他栏目 笔记2: 确切地说,(序列,修订)组合总是唯一的。
答案 0 :(得分:3)
此查询选择修订与同一序列的最大修订版匹配的所有记录,并返回同一记录的其他字段。
SELECT c.id, c.name, c.body, c.sequence
FROM contents c
WHERE
c.section_id = 74 AND
IFNULL(c.revision, -1) =
(SELECT
IFNULL(MAX(cx.revision), -1)
FROM
contents cx
WHERE
cx.section_id = 74 AND /* Added this */
cx.sequence = c.sequence)
ORDER BY sequence
答案 1 :(得分:1)
子查询:
SELECT sequence, max(revision) as maxrev FROM contents
WHERE section_id = 74
GROUP BY sequence
会给你一个带有(序列,修订版)对的结果,用于挑选你想要的记录(正如你所说的那样,这对值在表中是唯一的)。使用原始表的内部联接来挑选其他列:
SELECT c.id, c.name, c.body, c.sequence
FROM contents as c INNER JOIN
(SELECT sequence, max(revision) as maxrev FROM contents
WHERE section_id = 74 GROUP BY sequence) as p
ON (c.sequence = p.sequence AND c.revision = p.maxrev)
WHERE c.section_id = 74
ORDER BY c.sequence
根据(序列,修订版)对在整个表中是唯一的,还是仅在具有相同section_id的一组记录中,外部查询中的WHERE子句可能是多余的。
答案 2 :(得分:0)
GROUP BY和MAX()在你的情况下不起作用吗?
SELECT
id,
name,
body,
sequence as seq,
MAX(rev) as m_rev
FROM
`contents`
WHERE (`contents`.section_id = 74)
GROUP BY sequence
ORDER BY sequence ASC, rev DESC
答案 3 :(得分:0)
可能会使用以下内容:
SELECT id, name, body, sequence FROM contents c
WHERE section_id = 74 AND revision in ( SELECT MAX(revision) FROM contents WHERE
sequence=c.sequence) ORDER BY sequence ASC