我和the one solved here有类似的问题,但是当我尝试解决方案时,我认为它失败了,因为我的设置不同......
我有一张doc表... (遗憾的是,由于它是旧系统,因此无法编辑表格)
+-------+--------+----------+--------+
| Docid | title | revision | linkid |
+-------+--------+----------+--------+
| 1 | docone | 1 | 1 |
| 2 | doctwo | 1 | 2 |
| 3 | docone | 2 | 1 |
|4 | docone | 3 | 1 |
+-------+--------+----------+--------+
在列出所有文档的页面上,我只想列出每个文档的最新版本。例如,Doc1在修订版3上,所以我想要那个而不是其他2. Doc2只在修订版1上,所以显示一个。
基于另一篇文章中的问题,我将查询写成如下......
$query_docs = "
SELECT `document`.*, doctype.*
FROM `document`
INNER JOIN doctype
ON `document`.iddoctypes = doctype.iddoctypes
WHERE `document`.revision = (
SELECT MAX(`document`.revision) AS revision
FROM `document`
)
GROUP BY `document`.linkid
ORDER BY `document`.doccreation DESC";
我不得不链接到另一个表来获取文档类型(只是为了使查询更难)。
答案 0 :(得分:0)
只是猜测:我认为您必须在group by title
子查询中添加(select max(...) ...)
。
所以完整的陈述将是:
$query_docs = "
SELECT `document`.*, doctype.*
FROM `document`
INNER JOIN doctype
ON `document`.iddoctypes = doctype.iddoctypes
WHERE `document`.revision = (
SELECT MAX(`document`.revision) AS revision
FROM `document`
--GROUP BY `document`.title
GROUP BY `document`.linkid
)
GROUP BY `document`.linkid
ORDER BY `document`.doccreation DESC";
答案 1 :(得分:0)
试试这个,我做了一些小改动
SELECT document.*, doctype.*
FROM document
INNER JOIN doctype
ON document.iddoctypes = doctype.iddoctypes
WHERE document.revision = (
SELECT MAX(d1.revision)
FROM document d1
WHERE document.linkid = d1.linkid
)
ORDER BY document.doccreation DESC
答案 2 :(得分:0)
我错过了什么吗?这似乎完全是直截了当的......
SELECT x.*
FROM my_table x
JOIN (SELECT title,MAX(revision) max_revision FROM my_table GROUP BY title) y
ON y.title = x.title
AND y.max_revision = x.revision;