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

时间:2019-01-18 10:35:39

标签: mysql

我要选择包含不同电子邮件的行,请参见下面的示例表:

表名=用户

SESSION_COOKIE_DOMAIN

所需的结果将是:

 +----+---------+-------------------+-------------+
   | 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 | +----+-------+-------------------+-------------+ | 5 | its ok| rob@hotmail.com | rob | | 7 | nice! | simon@hotmail.com | simon | | 8 | yeah | john@hotmail.com | john | +----+-------+-------------------+-------------+ 中的最新条目 所需的SQL是什么?

3 个答案:

答案 0 :(得分:4)

如果您使用的是MySQL 5.7或更早版本,则可以将表加入一个子查询,该子查询查找每封电子邮件的最新记录:

2019-01-21 10:08:50 INFO  m.d.s.a.b.reader.PortalMessageReader - Portal Message Read by Thread id 115 - Thread name: poller_batch_thread115
2019-01-21 10:08:50 INFO  m.d.s.a.b.reader.PortalMessageReader - Portal Message Read by Thread id 116 - Thread name: poller_batch_thread116

如果您使用的是MySQL 8+,则只需在此处使用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;

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; 记录是id = 6的最新记录。

答案 1 :(得分:1)

您可以在下面使用相关子查询尝试

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

答案 2 :(得分:0)

如果'id'是唯一键或主键,则可以使用此键:

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

以上所述将提高数据库性能,因为correlated subqueries来自以下事实:子查询使用外部查询的信息,并且子查询对外部查询的每一行执行一次。因此,我建议您使用如果“ id”是唯一的,我的回答是。