简体   繁体   English

根据单个不同的列选择唯一行-MySQL

[英]Select Unique Rows Based on Single Distinct Column - MySQL

I want to select rows that have a distinct email, see the example table below: 我想选择包含不同电子邮件的行,请参见下面的示例表:

Table Name = Users 表名称=用户

 +----+---------+-------------------+-------------+
   | 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        |
   +----+---------+-------------------+-------------+

The desired result would be: 理想的结果将是:

 +----+-------+-------------------+-------------+
   | id | title | email             | commentname |
   +----+-------+-------------------+-------------+
   |  5 | its ok| rob@hotmail.com   | rob         |
   |  7 | nice! | simon@hotmail.com | simon       |
   |  8 | yeah  | john@hotmail.com  | john        |
   +----+-------+-------------------+-------------+

Distinct value should be latest entry in Table Example id = 6 What would be the required SQL? 不同的值应该是表示例中的最新条目id = 6所需的SQL是什么?

If you are using MySQL 5.7 or earlier, then you may join your table to a subquery which finds the most recent record for each email: 如果您使用的是MySQL 5.7或更早版本,则可以将表加入一个子查询,该子查询查找每封电子邮件的最新记录:

SELECT t1.id, t1.title, t1.email, t1.commentname
FROM yourTable t1
INNER JOIN
(
    SELECT email, MAX(id) AS latest_id
    FROM yourTable
    GROUP BY email
) t2
    ON t1.email = t2.email AND t1.id = t2.latest_id;

If you are using MySQL 8+, then just use ROW_NUMBER here: 如果您使用的是MySQL 8+,则只需在此处使用ROW_NUMBER

WITH cte AS (
    SELECT id, title, email, commentname,
        ROW_NUMBER() OVER (PARTITION BY email ORDER BY id DESC) rn
    FROM yourTable
)

SELECT id, title, email, commentname
FROM cte
WHERE rn = 1;

Note: Your expected output probably has a problem, and the id = 6 record is the latest for rob@hotmail.com . 注意:您的预期输出可能有问题,并且id = 6记录是rob@hotmail.com的最新记录。

You can try below using correlated subquery 您可以在下面尝试使用相关子查询

select * from table1 a
where id in (select max(id) from table1 b where a.email=b.email group by b.email)

If 'id' is unique or primary key you could use this one: 如果“ id”是唯一键或主键,则可以使用此键:

select * from Users where id in (select max(id) from Users group by commentname)

Above one would up your database performance because the correlated subqueries comes from the fact that the subquery uses information from the outer query and the subquery executes once for every row in the outer query.So,I will suggest you using my answer if 'id' is unique. 上面的一项将提高数据库性能,因为相关的子查询来自以下事实:子查询使用外部查询中的信息,并且子查询对外部查询中的每一行执行一次。因此,如果“ id”,我建议您使用我的答案是独特的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM