表:AssetManagment
id | serial | idcode
---|--------|-------
1 | 123 | 4
2 | 1234 | 4
表:AssetManagement_History
id | rowID | action | occurred
---|--------|-----------|-------------
1 | 1 | shipping | 2014-04-01
2 | 1 | stocked | 2014-04-02
3 | 1 | installed | 2014-04-03
4 | 2 | stocked | 2014-04-04
在此示例中,AssetManagement_History.rowID与AssetManagment.id相关,因此您可以看到第一个资产有三个历史详细信息,第二个资产只有一个。我需要返回 last 操作对应于'stocked'或'restocked'的所有资产 - 因此只应返回第二个资产。这是我尝试过的几个mySQL语句:
SELECT tblASSET.id,tblASSET.serial
FROM AssetManagement tblASSET
INNER JOIN
(SELECT occurred,max(id) id
FROM AssetManagement_History GROUP BY occurred) tblAH ON tblASSET.id = tblAH.rowID
WHERE tblASSET.idcode='4' AND tblAH.action IN ('stocked','restocked')
另一次尝试:
SELECT tblASSET.id,tblASSET.serial
FROM AssetManagement tblASSET
INNER JOIN
(SELECT max(rowID) rowID
FROM AssetManagement_History GROUP BY occurred) tblAH ON tblAH.rowID = tblASSET.id
WHERE tblASSET.idcode='4'
我还有其他几个,但他们也没有工作。非常感谢任何帮助!
谢谢, 戴夫
答案 0 :(得分:3)
SELECT
A.id,
A.serial
FROM AssetManagement A
INNER JOIN ( -- Join to get our latest history ID
SELECT
H.rowID,
MAX(H.ID) ID
FROM AssetManagement_History H
GROUP BY H.rowID
) H1
ON H1.rowID = A.id
INNER JOIN AssetManagement_History H2 -- Join to get the row for the latest history
ON H2.ID = H1.ID
WHERE
H2.action IN ('stocked', 'restocked')
AND
A.IDCode = 4
答案 1 :(得分:0)
SELECT tblASSET.id,tblASSET.serial
FROM AssetManagement AS tblASSET
INNER JOIN AssetManagement_History AS tblAH
ON tblAH.rowID = tblASSET.id
WHERE tblASSET.idcode='4'
您收到了哪些错误消息?您希望结果如何?
答案 2 :(得分:0)
尝试使用NOT EXISTS
,(解释在评论中)
SELECT tblASSET.id, tblASSET.serial
FROM AssetManagment AS tblASSET
INNER JOIN AssetManagement_History AS tblAH
ON tblAH.rowID = tblASSET.id
WHERE tblASSET.idcode = '4'
AND tblAH.action IN ('stocked','restocked')
--/*And not exists occurred that is greater for the same rowID*/
AND NOT EXISTS (SELECT 1 FROM AssetManagement_History AS his
WHERE his.rowID = tblAH.rowID
AND his.occurred > tblAH.occurred )
编辑:修改了查询中的错误,这是一个有效的SQL FIDDLE。
答案 3 :(得分:0)
这是一个格式化的评论而不是答案
此:
INNER JOIN
(SELECT occurred,max(id) id
FROM AssetManagement_History GROUP BY occurred) tblAH ON tblASSET.id = tblAH.rowID
会抛出错误,因为tblAH没有名为rowID的字段。这样:
INNER JOIN
(SELECT max(rowID) rowID
FROM AssetManagement_History GROUP BY occurred) tblAH ON tblAH.rowID = tblASSET.id
由于你的愚蠢子查询,可能会给出奇怪的结果。您正在按照您未选择的字段进行分组。单独运行该子查询,看它是否返回您期望的结果。
答案 4 :(得分:0)
我认为这就是你要找的东西。您需要对子查询中的操作应用where子句。
SELECT tblASSET.id,tblASSET.serial
FROM AssetManagement tblASSET
INNER JOIN (SELECT occurred,max(id) id
FROM AssetManagement_History
where action in IN ('stocked','restocked') GROUP BY occurred
) tblAH ON tblASSET.id = tblAH.id
WHERE tblASSET.idcode='4'