2012-12-27 253 views
3

我有一個項目表和另一個報告。每個報告都有一個外鍵鏈接到正在報告的項目。MySQL DELETE語句加入,HAVING和GROUP BY

我試圖刪除這個查詢中顯示的所有項目:

SELECT items.id, title, SUM(weight) AS total_weight, SUM(weight)*10/views AS score 
FROM items, reports 
WHERE items.id = reports.item_id 
GROUP BY items.id 
HAVING score >= 50; 

嘗試這樣的事:

DELETE items 
FROM (SELECT items.id, title, SUM(weight) AS total_weight, SUM(weight)*10/views AS score 
    FROM items, reports 
    WHERE items.id = reports.item_id 
    GROUP BY items.id 
    HAVING score >= 50) 
AS T; 

給我此錯誤消息:

ERROR 1109 (42S02): Unknown table 'items' in MULTI DELETE 

回答

4

在MySQL中,您必須小心子查詢。我認爲以下工作:

DELETE FROM items 
WHERE id IN (select * 
      from (SELECT items.id 
        FROM items join reports 
         on items.id = reports.item_id 
        GROUP BY items.id 
        HAVING SUM(weight)*10/views >= 50 
       ) 
      ) 

它使技巧編譯器通過使用額外的子查詢接受查詢。我還修復了您的join語法。

以下,雖然,改寫查詢轉換爲更通用的語法,使用一個相關子查詢:

delete from items 
where exists (select r.item_id 
       from reports r 
       where r.item_id = items.item_id 
       group by r.item_id 
       having SUM(r.weight)*10/items.views >= 50 
      ) 

這是猜測,weightviews在前面來自reports. Otherwise, you need to put the items`別名來代替。

+0

謝謝,戈登。權重來報告,但意見與項目。你的意思是把項目別名在前? – mukama

+0

謝謝戈登。非常翔實的答案,但由於某種原因沒有執行。@var ___的答案爲我工作。再次感謝。 – mukama

4
DELETE FROM items 
WHERE 
    id IN (
    SELECT 
     items.id 
    FROM items, reports 
    WHERE items.id = reports.item_id 
    GROUP BY items.id 
    HAVING SUM(weight)*10/views >= 50) 
+1

嗨GolezTrol,我得到這個錯誤:ERROR 1093(HY000):不能在FROM子句指定 – mukama

+0

目標表 '項目' 的更新顯然MySQL不會接受這個。請嘗試Gordon Linoff的答案。 – GolezTrol

2

我相信你的delete聲明是錯誤的。它應該是delete from tablename where [condition]

DELETE FROM items 
    WHERE 
     id IN (
     Select T.id from (SELECT items.id, title, SUM(weight) AS total_weight, SUM(weight)*10/views AS score 
FROM items, reports 
WHERE items.id = reports.item_id 
GROUP BY items.id 
HAVING score >= 50) T) 
+0

嗯...試了一下,但我得到這個錯誤:錯誤1064(42000):你的SQL語法錯誤; (SELECT items.id,title,SUM(weight)AS total_weight,SUM(weight)* 10/views AS sc'at line 1 – mukama

+0

顯然MySQL – GolezTrol

+0

@mcaesar我再次更新了查詢,請再次查詢。 – Ravi

1

試試這個:

DELETE FROM items 
WHERE id IN (SELECT id 
      FROM (SELECT i.id itemId, (SUM(weight) * 10/views) score 
        FROM items i INNER JOIN reports r ON i.id = r.item_id 
        GROUP BY itemId HAVING score >= 50 
       ) AS A 
      ); 
+0

謝謝薩哈什。var___的答案很好。得到錯誤:錯誤1054(42S22):'組聲明'中的未知列'items.id' – mukama

+0

@mcaesar檢查我更新的答案 –

+0

我去了錯誤說:錯誤1054(42S22):在'having子句'中的未知列'views' – mukama