我有这个MySql查询:
SELECT *
FROM Customer c
JOIN eHRDemographic ehD ON ehD.CxID = c.CustomerID
JOIN CustPrimaryWeight cpW ON cpW.CxID = c.CustomerID
WHERE c.CustomerID =22703
GROUP BY c.CustomerID
ORDER BY cpW.CustPrimaryWeightID DESC
这不能正常工作,因为CustPrimaryWeight表有多个条目,它只是加入第一个条目而不是更新的条目,因为ORDER语句似乎没有做任何事情。
有什么想法吗?
答案 0 :(得分:1)
答案 1 :(得分:1)
我不太确定你要做什么。如果要在加入之前对CustPrimaryWeight
表进行排序,可以尝试这样的操作。
SELECT *
FROM Customer c
JOIN eHRDemographic ehD ON ehD.CxID = c.CustomerID
JOIN (SELECT * FROM CustPrimaryWeight ORDER BY CustPrimaryWeightID DESC) cpW ON cpW.CxID = c.CustomerID
WHERE c.CustomerID =22703
GROUP BY c.CustomerID
但是,由于您按CustomerID进行分组,我认为您正在尝试为每位客户显示最大CustPrimaryWeight
数据。
SELECT *
FROM Customer c
JOIN eHRDemographic ehD ON ehD.CxID = c.CustomerID
JOIN (SELECT * FROM CustPrimaryWeight
WHERE CustPrimaryWeightID = (SELECT MAX(CustPrimaryWeightID)
FROM CustPrimaryWeight
WHERE CustomerID = c.CustomerID)
) cpW ON cpW.CxID = c.CustomerID
WHERE c.CustomerID =22703
GROUP BY c.CustomerID