MySQL与LIMIT 1的连接没有返回所需的结果

时间:2018-05-19 12:27:32

标签: mysql sql subquery left-join

我遇到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),对于我的生活,我看不出问题;我认为这是一个noob错误,但我只是没有看到它。

3 个答案:

答案 0 :(得分:1)

您有a LEFT JOIN b ON a.id = (sub-query)

您应该a LEFT JOIN b ON b.id = (sub-query)

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

答案 1 :(得分:1)

如果每个连接只需要一行,则应在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

答案 2 :(得分:0)

您的查询缺少实际的join条件:

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

我将相关条件切换为srvc_test而不是lctn_test。这并没有什么不同。我发现为此目的引用单个表格更简单。