根据Field从mysql表中选择唯一记录

时间:2017-11-13 13:13:30

标签: mysql

我在MySQL中有一个表,我存储了注册信息。

我需要根据电子邮件字段和ID字段

选择所有行,但只选择最新行

我的表:

table1

我需要

result table

2 个答案:

答案 0 :(得分:3)

select *
from yourTablename
where (id,email) in 
        (select max(id),email from yourTablename group by email);

内部加入的另一种方法:(正如蒂姆所建议的那样)

SELECT t1.*
FROM t t1
INNER JOIN
(
    SELECT email, MAX(id) AS max_id
    FROM t t2
    GROUP BY email
) t2
    ON t1.email = t2.email AND
       t1.id  = t2.max_id;

DEMO

答案 1 :(得分:0)

感谢您的回复。

使用

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT email, MAX(name) AS max_name
    FROM yourTable
    GROUP BY email
) t2
    ON t1.email = t2.email AND
       t1.name  = t2.max_name;

工作得很好。

由于