假设你有一张这样的表
users_cities_relations
|--id--|name|c-id|
|----------------|
| 1 |Tom | 2 |
| 2 |Mike| 3 |
| 3 |Eve | 2 |
| 4 |Tom | 2 |
正如您所见,用户Tom存在2次,具有相同的c-id。
现在我要做的是删除其中一行。
我想的是:
SELECT id FROM users u1, users u2
WHERE u1.name = u2.name
AND u1.c-id = u2.c-id;
然后用不同的声明删除它。
遗憾的是,这并不能归还我所需要的东西,如果我没记错的话,这就归还了所有的id。
答案 0 :(得分:1)
尝试这种方法
Delete u from users_c u , (
select max(id) as id, name, c_id
from users_c
group by name, c_id
having count(id) > 1) as temp
where u.id = temp.id and u.name = temp.name and u.c_id = temp.c_id;
或临时表删除重复记录
CREATE TEMPORARY TABLE temp_users(
id int,
name varchar(40),
c_id int
);
insert into temp_users
select max(id), name, c_id
from users_c
group by name, c_id
having count(id) > 1;
select * from users_c;
select * from temp_users;
delete u from users_c u, temp_users temp
where u.id = temp.id and u.name = temp.name and u.c_id = temp.c_id;
drop temporary table temp_users;