我有一个这样的表格:
id | firstname | lastname ---+-----------+---------- 1 | alex | marti 2 | mark | finger 3 | alex | marti 4 | ted | port
需要以以下形式返回firstname,lastname重复项:
firstname
lastname
1 | alex | marti 3 | alex | marti
我尝试这样做,select firstname, lastname from t group by firstname, lastname having count(*) > 1但这会返回类似
select firstname, lastname from t group by firstname, lastname having count(*) > 1
firstname | lastname ----------+---------- mark | finger alex | marti ted | port
而且我需要id重复的内容,但是当然select id, firstname, lastname from t group by id, firstname, lastname不起作用。
id
select id, firstname, lastname from t group by id, firstname, lastname
有任何想法吗?谢谢。
您需要汇总ID。如果仅需要其中之一的ID(例如,删除),则可以执行以下操作:
select max(id) id, firstname, lastname from t group by firstname, lastname having count(*) > 1
如果您想同时使用两个ID,并且知道不会超过2个,则可以执行以下操作:
select min(id) minid, max(id) maxid, firstname, lastname from t group by firstname, lastname having count(*) > 1
如果您想要所有重复项及其ID,则必须使用派生表,如Nitin Midha的回答。