我有这个查询会给我那些字段“username”重复的行:
SELECT id, jos_users.username, email, password, lastvisitDate
FROM jos_users
INNER JOIN (SELECT username
FROM jos_users
GROUP BY username HAVING count(id) > 1) dup
ON jos_users.username = dup.username;
我需要让那些lastvisitDate更低。
例如:
id | username | email | password | lastvisitDate |
1 | mylogin | | | 2014-10-15 16:42:42 |
2 | mylogin | | | 2014-10-16 16:42:42 |
如您所见,id = 1的行具有最低的lastvisitDate。我怎么能把这句话放在查询上? 我想要这个,因为我将使用此选项执行删除查询以删除重复的行。
答案 0 :(得分:2)
SELECT id, jos_users.username, email, password, lastvisitDate
FROM jos_users
INNER JOIN (SELECT username
FROM jos_users jb
where jb.lastvisitDate =
(select min(jb1.lastvisitDate)
from jos_users jb1
where jb1.username = jb.username)
GROUP BY username
HAVING count(id) > 1) dup
ON jos_users.username = dup.username;
答案 1 :(得分:0)
我可能会把它写成:
SELECT u.id, u.username, u.email, u.password, u.lastvisitDate
FROM jos_users u
WHERE EXISTS (SELECT 1 FROM jos_users WHERE username = u.username GROUP BY username HAVING count(id) > 1)
AND EXISTS (SELECT 1 FROM jos_users WHERE username = u.username GROUP BY username HAVING min(lastvisitDate) = u.lastvisitDate)
答案 2 :(得分:0)
您可以获得最短的上次访问日期并进行删除
DELETE J FROM jobusers J
INNER JOIN (
SELECT username, MIN(lastvisitDate) as lastVisitDate
FROM job_users
GROUP BY username HAVING count(id) > 1
)T
ON J.username = T.username
AND J.lastvisitDate = T.lastVisitDate