2014-03-12 69 views
0

我有一些數據一致性問題,由於一個錯誤而發生。SQL查詢崩潰PHPMYADMIN - 問題與查詢邏輯

現在我試圖對它進行整理,但是當我運行我的測試查詢的一部分phpmyadmin崩潰或在很長一段時間內變得沒有響應時出現問題。 我試着自己運行嵌套子查詢,他們工作正常。

基本上我試圖解決的問題是:

如何刪除重複resource_type=1 FROM geo_address從擁有所有用戶超過一個resource_type=1 WHERE用戶也有geo_addressresource_type=2

基本上這意味着如果用戶有一個和1 resource_type=2他有一個重複resource_type=1。如果用戶有2 resource_type=1但沒有resource_type=2那麼它會陷入另一種情況,我不在這裏解決。

我在我的SQL查詢的邏輯找到了巨大的麻煩

我至今想出了是這樣的,但我知道它fundamentaly錯了,因爲它崩潰

我怎麼能正確地構建我的查詢?

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 
     ) 
+1

可你給在sqlfiddle數據的例子嗎? –

+0

用戶具有「重複」記錄,哪一個是你想保留的記錄? – eggyal

+0

@eggyal如果存在重複,我想保留'resource_type = 1'的MIN(id)'記錄 –

回答

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) 
       ); 
+0

你用cnt計算什麼?沒有定義 –

+0

@JonathanThurft在'SELECT'中編輯了別名,但忘記在'HAVING'中修改。固定 – Alexander

+0

如果有重複,我想保留'最小(id)'與'resource_type = 1',如果有重複並刪除其他'resource_type = 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