2016-02-07 94 views
3

我有一個國家數據庫和另一個表稱爲區域。加入mySQL更新查詢

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


Zones 
[id, name, country_id] 

我正在使用以下查詢來匹配所有國家與他們的區域。

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 

所以基本上總之一個區域是狀態和輸出是這樣的。

+-----------------------------------------------------+----------+--- -----------------------------------------+------------+----------------+ 
| 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 

輸出是巨大的粘貼這裏,所以只顯示在結果

我想更新各國的狀態,以0那裏是沒有區域的末端。任何想法如何我可以通過mySQL做到這一點?

回答

5

可以使用not in這樣的:

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

由於工作完美。 – limit