2013-02-28 36 views
0

我有兩個表user和user_secondary。我必須獲取幾列並存儲在user_secondary中。現在這兩個表有一行讓我們說 - 用戶可能稍後更新並保存它的性別。但是這個條目在user_secondary中存儲爲null。現在我必須在user_secondary表中針對用戶更新此性別字段。我該怎麼做?如何更新從另一個表的默認空值列中選擇值的表的列?

無法定義鍵約束,因爲性別字段爲空值。

回答

1

不好意思,這兩張表怎麼相關?無論如何,此代碼可能充當樣本:

UPDATE user_secondary 
SET user_secondary.GENDER = (SELECT user1.usergender FROM user1 
          WHERE user1.userid = user_secondary.id) 
where user_secondary.GENDER IS NULL 
+0

whats user1 here? – 2013-02-28 08:30:52

+0

第一張桌子,我沒有把用戶,因爲它很常見。 – SalemRady 2013-02-28 08:32:24

0

循環遍歷每個用戶行,如果該字段爲空,則執行一個簡單的查詢以從user_secondary表中獲取它。然後使用該數據在用戶表上運行更新語句。

1
UPDATE user_secondary 
JOIN user ON user.id=user_secondary.id 
SET user_secondary.gender=user.gender 
WHERE user_secondary.gender IS NULL;