sql - 内连接上的多个主键

时间:2017-06-08 08:04:33

标签: mysql sql subquery max inner-join

我需要计算具有独特ItemID的所有行:带有该ItemID的项目上具有最高RevisionID的s。这是我的代码(相关部分):

(
SELECT count(parent.ItemID) FROM item AS parent
INNER JOIN item AS child ON parent.ItemID = child.ItemID AND parent.RevisionID = Max(child.RevisionID)
WHERE parent.orderID = orders.orderID AND parent.StatusInfo != '2' 
) as notordered,  

如果您取出“AND parent.RevisionID = Max(child.RevisionID)”,则代码可以工作,但是它会获取所有项目的修订版本。我知道我不能在INNER JOIN ON中使用“Max”,但我找不到一种方法来获得它与规则parent.ItemID = child.ItemID与子查询一致的方式。 请帮忙。

例:
输入
A-ID:1 RevID:2
B-ID:1 RevID:3
C-ID:2 RevID:4
返回:
B& C,因为它们具有唯一的ID:s和具有该ID的最高RevID

1 个答案:

答案 0 :(得分:0)

http://stackoverflow.com/questions/17882073/mysql-select-max-date-inside-a-join-statement/17882188#17882188暗示的正确答案是:

SELECT count(parent.ItemID) FROM item AS parent
JOIN (SELECT itemID, MAX(RevisionID) as MaxRevision FROM Item GROUP BY ItemID) as child ON parent.ItemID = child.ItemID AND parent.RevisionID = child.MaxRevision
WHERE parent.orderID = orders.orderID 
) as notordered,