2014-09-12 61 views
0

我在想如果product_id在其他表中没有分配任何category_id,我是否可以将产品状态更改为0。MYSQL更新加入为空

+------------+----------+ +------------+-------------+ 
| Product_id | Status | | Product_id | cateogry_id | 
+------------+----------+ +------------+-------------+ 
|  1  |  1 | |  1  |  10  | 
|  2  |  1 | |  3  |  20  | 
|  3  |  1 | +------------+-------------+ 
+------------+----------+ 

在结果我需要的product_id = 2不具有类别的状态是0 有一个MySQL查询是什么?

回答

5

简单,首先您需要得到的是,在表中的arent行..

表1与状态
表2表是用类别ID

  table1      table2 
+------------+----------+ +------------+-------------+ 
| Product_id | Status | | Product_id | cateogry_id | 
+------------+----------+ +------------+-------------+ 
|  1  |  1 | |  1  |  10  | 
|  2  |  1 | |  3  |  20  | 
|  3  |  1 | +------------+-------------+ 
+------------+----------+ 

所以现在运行表此查询来获取没有CATEGORY_ID

SELECT product_id 
FROM table1 t 
LEFT JOIN table2 t2 ON t2.product_id = t.product_id 
WHERE t2.product_id IS NULL 

现在更新,像这样

表1的行
UPDATE table1 t, 
( SELECT product_id 
    FROM table1 t 
    LEFT JOIN table2 t2 ON t2.product_id = t.product_id 
    WHERE t2.product_id IS NULL 
) t1 
SET t.status = 0 
WHERE t1.product_id = t.product_id 

DEMO

1

您可以使用左与更新加入为空

update product p 
left join product_relation pr on (p.Product_id = pr.Product_id) 
set p.Status = 0 
where pr.Product_id is null 

Demo

0

或者更简单的..如果它不表2中的所有发现:

Update table1 
Set status = 0 
Where Product_id not in (SELECT Product_id FROM table2)