假设你有一张这样的 table
users_cities_relations
|--id--|name|c-id|
|----------------|
| 1 |Tom | 2 |
| 2 |Mike| 3 |
| 3 |Eve | 2 |
| 4 |Tom | 2 |
如您所见,用户 Tom 使用相同的 c-id 出现了 2 次。
现在我想做的是删除其中一行。
我在想这样的事情:
SELECT id FROM users u1, users u2
WHERE u1.name = u2.name
AND u1.c-id = u2.c-id;
然后用不同的语句删除它。
遗憾的是,这并没有返回我需要的内容,如果我没记错的话,这返回了所有的 id。
最佳答案
尝试这种方法
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;
关于PHP - mySQL 如果行中有两个值则选择重复项并删除一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22277657/