根据单个不同的列select唯一的行

我想select具有distinct email行,请参阅下面的示例表:

 +----+---------+-------------------+-------------+ | id | title | email | commentname | +----+---------+-------------------+-------------+ | 3 | test | rob@hotmail.com | rob | | 4 | i agree | rob@hotmail.com | rob | | 5 | its ok | rob@hotmail.com | rob | | 6 | hey | rob@hotmail.com | rob | | 7 | nice! | simon@hotmail.com | simon | | 8 | yeah | john@hotmail.com | john | +----+---------+-------------------+-------------+ 

预期的结果是:

 +----+-------+-------------------+-------------+ | id | title | email | commentname | +----+-------+-------------------+-------------+ | 3 | test | rob@hotmail.com | rob | | 7 | nice! | simon@hotmail.com | simon | | 8 | yeah | john@hotmail.com | john | +----+-------+-------------------+-------------+ 

我不关心哪个id列值被返回。 什么是必需的SQL?

在TSQL中快速一个

 SELECT a.* FROM emails a INNER JOIN (SELECT email, MIN(id) as id FROM emails GROUP BY email ) AS b ON a.email = b.email AND a.id = b.id; 

我假设你的意思是你不关心哪一行是用来获得titleidcommentname值(你对所有的行都“抢”了,但是我不知道这是不是真的将在您的数据模型中执行或不执行)。 如果是这样,那么你可以使用窗口函数返回给定电子邮件地址的第一行:

 select id, title, email, commentname from ( select *, row_number() over (partition by email order by id) as RowNbr from YourTable ) source where RowNbr = 1 

既然你不在乎哪个id返回,我坚持每个电子邮件的MAX id,以简化SQL查询,试试看

 ;WITH ue(id) AS ( SELECT MAX(id) FROM table GROUP BY email ) SELECT * FROM table t INNER JOIN ue ON ue.id = t.id 

如果您使用MySql 5.7或更高版本 ,根据这些链接( MySql官方 , SO QA ),我们可以select一group bylogging,而不需要任何聚合函数。

所以查询可以简化到这个。

select * from comments_table group by commentname;

在这里试试这个查询