由于一个错误,我遇到了一些数据一致性问题。
现在我正在尝试对其进行排序,但不知何故,当我运行部分测试查询phpmyadmin
崩溃或在很长一段时间内没有响应时。
我试着自己运行嵌套的子查询,它们工作正常。
基本上我要解决的问题是:
如何从具有多个resource_type=1
的所有用户中删除重复的geo_address
FROM resource_type=1
FROM该用户还拥有geo_address
resource_type=2
的用户
基本上,这意味着如果用户有2 resource_type=1
和1 resource_type=2
,则他有resource_type=1
重复。如果用户有2个resource_type=1
但没有resource_type=2
,那么它将落入我未在此处解决的不同情况。
我发现我的SQL
查询
到目前为止我得到的是这个,但我知道它的根本错误,因为它崩溃了
我如何正确构建查询?
SELECT member_num
FROM geo_address2
WHERE id IN (SELECT id
FROM geo_address2
WHERE resource_type=1
GROUP BY member_num
HAVING COUNT(resource_type) > 1
)
AND id IN (SELECT id
FROM geo_address2
WHERE resource_type=2
GROUP BY member_num
HAVING COUNT(resource_type) = 1
)
答案 0 :(得分:2)
经过一番讨论后,我编辑了答案 一种选择是使用此查询:
DELETE
FROM geo_address2
WHERE id IN (SELECT DISTINCT g12.id
FROM (SELECT member_num,
id
FROM geo_address2
WHERE resource_type = 1) g1
JOIN
(SELECT member_num,
id
FROM geo_address2
WHERE resource_type = 1) g12
ON g1.member = g12.member AND g1.id > g12.id
(SELECT member_num,
id
FROM geo_address2
WHERE resource_type = 2) g2
ON g1.member_num = g2.member_num
);
第二个(我相信它在逻辑上是一样的):
DELETE
FROM geo_address2
WHERE id IN (
SELECT g1.id
FROM geo_address2 g0
JOIN geo_address2 g1
ON (g0.member_num = g1.member_num
AND g0.id > g1.id
AND g0.resource_type = 1
AND g1.resource_type = 1)
JOIN geo_address2 g2
ON (g1.member_num = g2.member_num
AND g0.resource_type = 1
AND g2.resource_type = 2)
);
答案 1 :(得分:0)
DELETE dupe
FROM geo_address2 dupe
JOIN geo_address2 keep
ON dupe.id > keep.id
AND dupe.member_num = keep.member_num
AND dupe.resource_type = keep.resource_type
JOIN geo_address2 save
ON save.member_num = dupe.member_num
AND save.resource_type = 2
WHERE dupe.resource_type = 1