2015-11-03 83 views
-3

我有兩個表:空值不考慮在插入查詢

DistrictMaster

----------------------------------------------------- 
DistrictID  |  DistrictName | State 
----------------------------------------------------- 
    21   |   ABC   | ktm 
    22   |   XYZ   | ktm 
    32   |   PQR   | johar 
----------------------------------------------------- 

Districtdetail

District  | DistrciID | State | Country 
------------------------------------------------ 
PQR   |    | johar | MY 
null   |    | Kedah | MY 
ABC   |    | ktm  | MY 
       |    | Kedah | MY 
XYZ   |    | ktm  | MY 
------------------------------------------------ 

我需要Districtdetail插入DistrictID哪些有幾個空值和沒有值。我用下面的查詢,但它不是二廳。

insert into Districtdetail(DistrictID) 
    select 
     a.id 
    from 
     DistrictMaster a 
    left join 
     Districtdetail b on a.DistrictName = b.DistrictName 
         and a.State = b.State; 

上面的查詢是說執行,但沒有插入任何內容。

+0

'insert'用於創建新* *行。我懷疑你想更新*現有*行,所以你應該看看'update'。 –

+0

@Damien_The_Unbeliever我可以使用更新表中的連接嗎? – vim

+0

在SQL Server中,您可以在UPDATE中使用聯接。但這是非標準的,可能不會轉化爲其他數據庫系統。 –

回答

4

這是簡單的UPDATE語句加入:

update d 
set DistrictID = m.DistrictID 
from DistrictMaster m 
join Districtdetail d on m.DistrictName = d.District and m.State = d.State 
+1

它說0行受到影響 – vim

+1

這意味着你在這些表中沒有相關數據......或者你在數據或隱藏符號中有一些空格,如新行或標籤...... –

0

你可能有麻煩做的,如果主鍵未在加入保存聯接更新。 在這種情況下,你應該嘗試更新Districtdetail這樣:

update Districtdetail dd 
set dd.DistrictID = (select dm.DistrictID 
         from DistrictMaster dm 
         where dm.DistrictName = dd.District 
         and dm.State = dd.State) 
where exists 
(select * 
    from DistrictMaster dm 
    where dm.DistrictName = dd.District 
    and dm.State = dd.State)