假设我的SQL数据库中有三列,如
ID | NAME | PHONE
-----------------
1 | JEFF | 467
2 | JEFF | 489
3 | JOHN | 234
4 | JACK | 323
5 | JEFF | 378
我想编写一个SQL查询,删除检测到每NAME
次出现的所有行。这意味着在运行SQL查询后,该表应如下所示:
ID | NAME | PHONE
-----------------
1 | JEFF | 467
2 | JOHN | 234
3 | JACK | 323
非常感谢你!
非常感谢,我现在把它改成了
delete from product_list y
where exists (select 1 from product_list y2 where y.model = y2.model and y2.linkid < y.linkid);
但我总是得到这个错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'delete * from product_list y where exists (select 1 from product_list y2 whe' at line 3
提前致谢!
答案 0 :(得分:5)
标准的SQL方法是:
delete from yourtable y
where exists (select 1 from yourtable y2 where y.name = y2.name and y2.id < y.id);
即,删除存在具有相同名称和较低ID的记录的所有记录。
如果您只想返回行,请使用相同的想法:
select y.*
from yourtable y
where not exists (select 1 from yourtable y2 where y.name = y2.name and y2.id < y.id);
答案 1 :(得分:0)
我认为这个查询应该有效。在此查询中,Employee是我的表名,Employee-id是密钥。
DELETE from Employee WHERE EmpID in(select EmpID from Employee GROUP BY EmpId HAVING COUNT(*) >1)