我想知道如果product_id在其他表中没有分配任何category_id,我可以将产品状态更改为0。
+------------+----------+ +------------+-------------+
| Product_id | Status | | Product_id | cateogry_id |
+------------+----------+ +------------+-------------+
| 1 | 1 | | 1 | 10 |
| 2 | 1 | | 3 | 20 |
| 3 | 1 | +------------+-------------+
+------------+----------+
结果我需要没有类别状态的product_id = 2为0。 是否有一个MySQL查询?
答案 0 :(得分:5)
首先,您需要获取表中不存在的行..
table1是状态为
的表
table2是类别为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
现在像这样更新table1
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
答案 1 :(得分:1)
您可以在更新中使用左连接,其中包含null
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
答案 2 :(得分:0)
或者更简单..如果在table2中根本找不到它:
Update table1
Set status = 0
Where Product_id not in (SELECT Product_id FROM table2)