查询以获取最新版本(如果有)或仅获取文档

时间:2013-06-12 15:33:26

标签: mysql join

我有两个表DocumentsRevisions

文件表

+--------+--------------------+
| DataID |    Description     |
+--------+--------------------+
|      1 | This is document 1 |
|      2 | This is document 2 |
|      3 | This is document 3 |
|      4 | This is document 4 |
|      5 | This is document 5 |  
+--------+--------------------+

修订表

+--------+---------+-----------+
| DataID | Version |   State   |
+--------+---------+-----------+
|      1 |       1 | Published |
|      2 |       1 | Published |
|      3 |       1 | ?         |
|      3 |       2 | Published |
|      4 |       1 | Published |
+--------+---------+-----------+

所需输出

+--------+--------------------+---------+
| DataID |    Description     | Version |
+--------+--------------------+---------+
|      1 | This is document 1 | 1       |
|      2 | This is document 2 | 1       |
|      3 | This is document 3 | 2       |
|      4 | This is document 4 | 1       |
|      5 | This is document 5 | N/A     |
+--------+--------------------+---------+

我的查询:

SELECT d.*, h.version 
FROM documents d 
LEFT revisions h 
   ON h.dataID=d.dataID 
LEFT JOIN ( 
           SELECT dataID, MAX(version) as version 
           FROM revisions 
           GROUP BY dataID 
         ) dh 
    ON dh.dataID=h.dataID 
    AND dh.version=h.version 
    AND h.state='Published'

这个左连接的问题它还会列出version 1 docid 3state ?,而我只想要已发布的版本,如果有的话,只有列表列表文档版本为NULL。

修改 请注意,如果找到条目而不仅仅是版本号,我还希望revision数据中的所有列数据 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

通过从h.state子句中对WHERE进行过滤,您隐式将外连接转换为内连接;您应该将该条件放在连接条件中:

SELECT   d.*, MAX(h.Version)
FROM     documents d LEFT JOIN revisions h
      ON h.DataID = d.DataID
     AND h.state  = 'Published'
GROUP BY DataID

sqlfiddle上查看。

答案 1 :(得分:0)

试试这个:

SELECT d.*, dh.version FROM document d 
LEFT JOIN ( 
           SELECT dataID, MAX(version) as version, state
           FROM revisions 
           GROUP BY dataID,version 
         ) dh 
    ON dh.dataID=d.dataID 
    AND dh.state='Published';

这是SQLFiddle