2

我有两张桌子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 1docid 3state ?而我只想要发布的版本(如果有的话),否则,只需列出版本为 NULL 的列表文档。

编辑:请注意,如果它找到条目而不仅仅是版本号 ,我还想要数据中的所有列数据 有人可以帮忙吗?revision

4

2 回答 2

3

通过h.stateWHERE子句中过滤,您隐式地将外部联接转换为内部联接;您应该将该条件放在连接条件中:

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上查看。

于 2013-06-12T15:54:55.193 回答
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

于 2013-06-12T15:56:43.077 回答