2011-12-08 31 views
0

我有表categories選擇/更新,所有孩子的狀態= 0

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

如何我可以選擇和更新,其中有狀態的所有子類別類別的狀態= 0(在這個例子中,它只是categories_id 2)?我需要在PHP中集成這個。

由於提前,

亞歷

回答

1
update categories, 
(
    select parent_id, sum(categories_status) as cnt 
    from categories 
    where parent_id!=0 
    group by parent_id 
    having cnt=0 
) as child_cat 
set ? = ? /* what do you want to update? */ 
where categories.categories_id=child_cat.parent_id 

可能你沒有使用PHP,一個SQL就行了。

+0

太棒了!謝謝 – Alex

+0

歡迎你 – ajreal

1

我測試了這個在MSSQL所以語法可能會有點不同,但我相信這是你所追求的:

SELECT * FROM <table_name> WHERE parent_id NOT IN 
(
    SELECT parent_id 
    FROM <table_name> 
    WHERE categories_status = 1 
    GROUP BY parent_id 
) 

更新查詢:

UPDATE <table_name> 
SET categories_status = 1 
WHERE parent_id NOT IN 
(
    SELECT parent_id 
    FROM <table_name> 
    WHERE categories_status = 1 
    GROUP BY parent_id 
) 

的想法是隔離您希望從基本查詢中排除的parent_ids。您可以使用子查詢來實現這一點。

+0

很酷謝謝你! – Alex