2011-12-08 119 views
2

我有一個主表categories這樣如何使用子查詢更新表在where子句

categories_id | categories_status | parent_id 
    1     1    0 
    2     1    0 
    3     1    1 
    4     1    2 
    5     1    1 
    6     1    2 

和參考表products_to_categories

categories_id | products_id 
     3    778 
     3    998 
     5    666 
     5    744 

我選擇所有沒有子類別的類別:

SELECT * FROM categories 
WHERE categories_id not in (SELECT parent_id FROM categories) 
# gets entries with id 3, 4, 5, 6 

而且沒有參考表中的產品:

AND categories_id NOT IN (SELECT categories_id FROM products_to_categories) 
# gets entries with id 4, 6 

現在我想更新此結果categories_status但它不工作只是改變選擇要更新:

UPDATE categories 
SET categories_status = 0 
WHERE categories_id not in (SELECT parent_id FROM categories) 
AND categories_id NOT IN (SELECT categories_id FROM products_to_categories) 

有幾個類似的問題,但我想不出如何改變我的例子...

感謝&問候,

亞歷

回答

2

相反子查詢中,使用左外連接

update 
categories c1 
left outer join categories c2 on c1.ID = c2.Parent_id 
left outer join products_to_categories p on c1.categories_id = p.categories_id 
set c1.categories_status = 0 
where c2.ID is null and p.categories_id is null 
+0

我恨它,當人們使它看起來那麼容易。它讓我看起來很蠢);但是這是它,謝謝! – Alex

2

您無法更新包含在子查詢中的條件。 嘗試使用直接條件,如:

// this rely that all categories_id higher than 0 should be valid relations 
WHERE categories_id < 1 

..this應該工作,但我想給你有關性能的建議 - 在記錄的情況下,沒有父母使用NULL值。 比條件應該是WHERE categories_id IS NULL