2015-11-19 89 views
0

我有一個表看起來像這樣MySQL查詢模擬版本號

+-----------+---------+-------+------------------------+-----------------------+ 
| commentID | reftype | refID |  comment   |  timestamp  | 
+-----------+---------+-------+------------------------+-----------------------+ 
|   1 | A  | 123 | Comment 1    | 2015-11-19 09:05:18 | 
|   1 | A  | 123 | Comment 1, First edit | 2015-11-19 09:06:18 | 
|   2 | A  | 123 | Comment 2    | 2015-11-19 09:05:44 | 
|   1 | A  | 123 | Comment 1, Second edit | 2015-11-19 10:05:23 | 
+-----------+---------+-------+------------------------+-----------------------+ 

我的目標是選擇每個評論的最新編輯和添加一個版本號列。所以,我希望的結果是這樣的

+-----------+---------+-------+------------------------+---------------------+-----+ 
| commentID | reftype | refID |  comment   |  timestamp  | rev | 
+-----------+---------+-------+------------------------+---------------------+-----+ 
|   1 | A  | 123 | Comment 1, Second edit | 2015-11-19 10:05:23 | 3 | 
|   2 | A  | 123 | Comment 2    | 2015-11-19 09:05:44 | 1 | 
+-----------+---------+-------+------------------------+---------------------+-----+ 

使用下面的查詢我得到相當接近,但我怎麼得到我的修訂列?我的方法可能嗎?還是需要完全改變它?

SELECT c1.* 
FROM comments c1 
LEFT JOIN comments c2 ON (c1.commentID = c2.commentID AND c1.timestamp < c2.timestamp) 
WHERE c2.timestamp IS NULL 
AND c1.referencetype = 'A' 
AND c1.referencekey = 123 
ORDER BY timestamp DESC 

上述查詢給我

+-----------+---------+-------+------------------------+---------------------+ 
| commentID | reftype | refID |  comment   |  timestamp  | 
+-----------+---------+-------+------------------------+---------------------+ 
|   1 | A  | 123 | Comment 1, Second edit | 2015-11-19 10:05:23 | 
|   2 | A  | 123 | Comment 2    | 2015-11-19 09:05:44 | 
+-----------+---------+-------+------------------------+---------------------+ 

回答

1

你可以得到的最新修訂版計數在一個單一的聚合子查詢:

SELECT c1.*, c2.numcomments as rev 
FROM comments c1 JOIN 
    (SELECT c2.commentId, COUNT(*) as numcomments, 
      MAX(timestamp) as maxtx 
     FROM comments 
     WHERE c2.referencetype = 'A' AND c2.referencekey = 123 
     GROUP BY c2.commentId 
    ) c2 
    ON c1.commentId = c2.commentId 
ORDER BY timestamp DESC ; 
1
SELECT T1.*,T2.`rev` 
    FROM 
     table_name T1 
    INNER JOIN 
    (SELECT T.`commentID`,T.`reftype`,MAX(T.`timestamp`) AS timestamp,(SELECT COUNT(*) FROM table_name WHERE table_name.`commentID` = T.`commentID` AND table_name.`reftype` = T.`reftype`) AS rev FROM table_name T GROUP BY T.'reftype',T.`commentID`) T2 
    ON 
    T2.`commentID` = T1.`commentID` AND T2.`reftype` = T1.`reftype` AND T1.`timestamp`= T2.`timestamp` 
+0

謝謝,但我不沒辦法。我如何從此獲取修訂號碼? – daker

+0

我編輯過,請檢查.... –