如何为“GROUP BY```列返回最高ID NON NULL字段?

时间:2018-05-02 16:10:57

标签: mysql sql

SELECT email, first_name, last_name from person group_by email order by id desc

如果first_name混合了值和空值,我将如何获得该列的最新NOT NULL值?

id | email   | first_name   | last_name
1  | a@b.com |  ted         | smith
2  | a@b.com |  zed         | smith
3  | a@b.com |  NULL        | johnson

我基本上想要获得first_name的值zed。

4 个答案:

答案 0 :(得分:0)

假设您有一个具有排序的person_id列,您只需执行以下操作:

select p.*
from person p
where (email, person_id) in (select p2.email, max(p2.person_id)
                             from person p2
                             where p2.first_name is not null
                             group by p2.email
                            );

答案 1 :(得分:0)

可能是此查询解决您的问题

SELECT p.email, p.first_name, p.last_name 
from person p
where  p.id = (SELECT max(id) from person where id = p.id and first_name is not null)
group_by p.email 
order by p.id desc

答案 2 :(得分:0)

我会在这里使用suquery

SELECT *
from person p
where id = (select max(id) 
            from person 
            where email = p.email and 
                  first_name is not null) 
order by id desc;

答案 3 :(得分:0)

伙计们感谢您的帮助。

我找到了我需要的答案。您实际上可以在GROUP_CONCAT中输入订单!

SUBSTRING_INDEX(GROUP_CONCAT(first_name ORDER BY id desc), ',', 1) as recent_first_name

它按ID分组first_name个订单,然后根据子串逗号分隔抓取最新的一个。

另外,默认情况下GROUP_CONCAT过滤器NULL很酷!