简体   繁体   English

关于连接的mySQL更新查询

[英]mySQL update query on join

I have a countries database and another table called zones. 我有一个国家数据库和另一个名为区域的表。

Countries 
[id, name, status (1 enabled 0 disabled) ]


Zones 
[id, name, country_id]

I am using the following query to match up all countries with their zone. 我使用以下查询来匹配所有国家/地区的区域。

select 
z.name as state, 
z.id as state_id, 
c.name as country_name, 
c.id as country_id, 
c.status as country_status 
from countries c left join zones z on c.id = z.country_id 

So basically in short a Zone is the state and the output is like this. 所以基本上简而言之,区域是状态,输出就是这样。

+-----------------------------------------------------+----------+---   -----------------------------------------+------------+----------------+
| state                                               | state_id | country_name                               | country_id | country_status     |
+-----------------------------------------------------+----------+---  -----------------------------------------+------------+----------------+
| NULL                                                |     NULL | Christmas Island                           |         45 |              1   
| NULL                                                |     NULL | Puerto Rico                                |        172 |              1    
| NULL                                                |     NULL   Isle of Man                                |        254 |              1  
| Álava                                        |     2971 | Spain                                      |        195 |              1   
| Ávila                                        |     2976 | Spain                                      |        195 |              1 
| Évora                                        |     2656 | Portugal                                   |        171 |              1   

The output is huge to paste here so only showing in the end of the result 输出很大,粘贴在这里,所以只显示在结果的末尾

I want to update the status on countries to 0 where there is no zone. 我想将国家/地区的状态更新为0,其中没有区域。 Any idea how I can do this via mySQL? 知道我怎么能通过mySQL做到这一点?

您可以使用not in这样的:

 update Countries set status=0 where id not in (select distinct country_id from Zones )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM