Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MYSQL更新联接为null_Mysql_Sql - Fatal编程技术网

MYSQL更新联接为null

MYSQL更新联接为null,mysql,sql,Mysql,Sql,我想知道,如果product\u id未在其他表中分配任何category\u id,是否可以将product status更改为0 +------------+----------+ +------------+-------------+ | Product_id | Status | | Product_id | cateogry_id | +------------+----------+ +------------+-------------+ | 1 |

我想知道,如果product\u id未在其他表中分配任何category\u id,是否可以将product status更改为0

+------------+----------+  +------------+-------------+
| Product_id |  Status  |  | Product_id | cateogry_id |
+------------+----------+  +------------+-------------+
|      1     |     1    |  |     1      |      10     |
|      2     |     1    |  |     3      |      20     |
|      3     |     1    |  +------------+-------------+
+------------+----------+
在结果中,我需要没有类别状态的product_id=2为0。
有一个MySQL查询吗?

Simple首先需要获取表中没有的行

表1是状态为
表2是具有类别id的表

           table1                     table2
+------------+----------+  +------------+-------------+
| Product_id |  Status  |  | Product_id | cateogry_id |
+------------+----------+  +------------+-------------+
|      1     |     1    |  |     1      |      10     |
|      2     |     1    |  |     3      |      20     |
|      3     |     1    |  +------------+-------------+
+------------+----------+
因此,现在运行此查询以获取没有category\u 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

您可以在更新中使用left join,其值为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中根本找不到:

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