我在sql中写了一个查询,我将只保留一次Companies.ID,这就是我使用Distinct的原因。
SELECT DISTINCT Companies.ID, Companies.Company, Abo.Ende
FROM Companies
LEFT JOIN Abo on Companies.ID = Abo.CompanyID
ORDER BY Abo.Ende
表Abo.Ende有更多的Abo.CompanyID条目,我希望得到最新的Abo.Ende不同的Companies.ID。注意:Abo.Ende是一个日期时间字段,我想获得最新的。
我想知道这是否是最好的方法。还有另一种方式吗?
答案 0 :(得分:4)
您需要group by
,而不是distinct
:
SELECT Companies.ID, Companies.Company, max(Abo.Ende)
FROM Companies
LEFT JOIN Abo on Companies.ID = Abo.CompanyID
GROUP BY Companies.ID, Companies.Company
对DISTINCT
用法的评论:
DISTINCT
在整个行上运行。因此,它将返回单行中所有列值的不同组合。如果您包含PK列(在您的情况下可能为companies.id
),则不会“删除”任何行,因为PK根据定义是唯一的,并且如果一列在所有行中是唯一的,那么结果的所有列是“独特的”(在DISTINCT
运算符的意义上)。
答案 1 :(得分:1)
尝试:
SELECT Companies.ID,
Companies.Company,
MAX(Abo.Ende) AS Ende
FROM Companies
LEFT JOIN Abo on Companies.ID = Abo.CompanyID
GROUP BY Companies.ID,
Companies.Company
答案 2 :(得分:1)
SELECT Companies.ID, Companies.Company, max(Abo.Ende)
FROM Companies
LEFT JOIN Abo on Companies.ID = Abo.CompanyID
GROUP BY Companies.ID, Companies.Company