使用连接和组排序MySQL查询

时间:2010-04-29 11:56:19

标签: mysql

我有这个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语句似乎没有做任何事情。

有什么想法吗?

2 个答案:

答案 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