我在使用SQL查询时遇到麻烦;我正在尝试获取每个“资产”的最后服务日期。

我正在尝试将左联接与子查询限制为1。

这是我的桌子:

lctn_test

testID, cleintID
1,      34
2,      34


srvc_test

srvcTestID, testID, serviceDate,            servicePassed
1,          1,      2018-05-19 03:23:53,    1
2,          1,      2018-05-19 11:46:49,    1
3,          2,      2018-05-19 11:47:24,    1


这是我尝试过的(以及一些变化)

SELECT
    lctn.testID AS assetID, lctn.ClientID,
    srvc_test.serviceDate, srvc_test.servicePassed
FROM
    lctn_test AS lctn
LEFT JOIN
    srvc_test ON lctn.testID = (SELECT srvc_test.testID
                                FROM srvc_test
                                WHERE srvc_test.testID = lctn.testID
                                ORDER BY srvc_test.serviceDate DESC
                                LIMIT 1)
WHERE
    lctn.ClientID = 34
ORDER BY
    assetID


我期望得到什么:

assetID,    ClientID,   serviceDate,            servicePassed
1,          34,         2018-05-19 11:46:49,    1
2,          34,         2018-05-19 11:47:24,    1


但这实际上是我得到的:

assetID,    ClientID,   serviceDate,            servicePassed
1,          34,         2018-05-19 03:23:53,    1
1,          34,         2018-05-19 11:46:49,    1
1,          34,         2018-05-19 11:47:24,    1
2,          34,         2018-05-19 03:23:53,    1
2,          34,         2018-05-19 11:46:49,    1
2,          34,         2018-05-19 11:47:24,    1


我仍在学习SQL(mysql),终生看不到问题。我敢打赌这是一个菜鸟的错误,但我看不到它。

最佳答案

如果每个联接只需要一行,则应在ON子句中使用联接表的UNIQUE(或PRIMARY)KEY。那可能是srvc_test.srvcTestID

SELECT lctn.testID AS assetID, lctn.ClientID, srvc_test.serviceDate, srvc_test.servicePassed
FROM lctn_test AS lctn
LEFT JOIN srvc_test ON srvc_test.srvcTestID = (
    SELECT srvc_test.srvcTestID
    FROM srvc_test
    WHERE srvc_test.testID = lctn.testID
    ORDER BY srvc_test.serviceDate DESC
    LIMIT 1)
WHERE lctn.ClientID = 34
ORDER BY assetID

10-06 03:48