0

I have a similar problem to the one solved here, but when I try the solution I think it fails because I have things set up differently..

I have a doc table with... (unfortunately table cant be edited due to it being an old system)

+-------+--------+----------+--------+
| Docid | title  | revision | linkid |
+-------+--------+----------+--------+
| 1     | docone | 1        | 1      |
| 2     | doctwo | 1        | 2      |
| 3     | docone | 2        | 1      |
|4      | docone | 3        | 1      |
+-------+--------+----------+--------+

On a page that lists all the documents I want to list only the latest revision of each document. Doc1 for example is on revision 3 so I want that one and not the other 2. Doc2 is only on revision 1 so show that one.

Based on the problem in the other post I have writen my query as follows......

$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";

I have had to link to another table to get the document type (just to make the query harder).

4

3 回答 3

0

Just a wild guess: I think you have to add group by title in your (select max(...) ...) subquery.

So the complete statement will be this:

$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";
于 2013-05-30T16:11:24.560 回答
0

Try this, I made a couple minor changes

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
于 2013-05-30T16:15:27.853 回答
0

Am I missing something? This seems completely straightforward...

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;
于 2013-05-30T16:20:53.647 回答