Am试图使用带有where子句的select查询来获取记录,显示id重复记录,然后我想按createdAt
字段对其进行过滤。
在运行以下查询并获得如下结果时:
select * from security_development.user_requests
where
fully_approved = 1 and user_request_role=4
请找到结果
createdAt User_request_name fully_approved user_request_role
2019-02-22 18:57:08 dealerAdmin 1 4
2019-02-24 08:57:08 ask1 1 4
2019-02-25 12:20:22 dealerAdmin 1 4
如果我尝试通过使用User_request_name
作为子查询来仅避免重复的max(creaTed_at)
,
select * from security_development.user_requests
where fully_approved =1 and user_request_role=4
created_at =
(select max(creaTed_at) from security_development.user_requests group by user_request_name having count(user_request_name) > 1 )
然后得到以下结果
createdAt User_request_name fully_approved user_request_role
2019-02-25 12:20:22 dealerAdmin 1 4
但希望获得以下结果
createdAt User_request_name fully_approved user_request_role
2019-02-24 08:57:08 ask1 1 4
2019-02-25 12:20:22 dealerAdmin 1 4
答案 0 :(得分:1)
您可以使用相关子查询
select t1.* from security_development.user_requests t1
where
fully_approved = 1 and user_request_role=4
and createdAt=( select max(createdAt)
from security_development.user_requests t2
where t1.User_request_name=t2.User_request_name)
答案 1 :(得分:0)
与问题不完全相同
要删除保存最新的现有重复项,请执行以下操作:
DELETE t1 FROM user_requests t1
INNER JOIN user_requests t2
WHERE t1.createdAt < t2.createdAt AND t1.user_request_name = t2.user_request_name
为防止插入重复的User_request_name
:
Alter table user_requests
add unique key (User_request_name);