SQL获得不同的名字和姓氏

时间:2013-08-02 19:10:33

标签: mysql sql distinct

我在这里有select distinct id, FirstName, LastName from table

这个问题

这会返回一个人员列表,首先是一些ID返回重复项,但我使用distinct来解决这个问题,但我仍然遇到问题,而且有些人是重复的。

是否还要在名字和姓名上加上明显的名称? (某些结果不带有id)

结果(没有明显的ID):

id - 01 - firstname - james - lastname - smith
id - 01 - firstname - james - lastname - smith
id - 02 - firstname - john - lastname - hicks
id - 02 - firstname - john - lastname - hicks
id -    - firstname - tom - lastname - nicks
id -    - firstname - tom - lastname - nicks

期待:

id - 01 - firstname - james - lastname - smith
id - 02 - firstname - john - lastname - hicks
id -    - firstname - tom - lastname - nicks

1 个答案:

答案 0 :(得分:5)

您有重复项,因为您在id中包含select

select distinct FirstName, LastName
from table;

如果您需要id作为名称,请使用group by

select min(id) as id, FirstName, LastName
from table
group by FirstName, LastName;

编辑:

如果您仍然使用这些查询获得重复项,那么您的名称中的字符会丢弃。我将首先修剪前导和尾随空格,看看这是否解决了重复问题:

select min(id) as id, trim(FirstName) as FirstName, trim(LastName) as LastName
from table
group by trim(FirstName), trim(LastName);