2011-12-08 29 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