2009-10-19 78 views
2

我有一個出生日期,年,月,日列其中列「年,月,日」是其他表的外鍵 我想要做的是每個出生日期得到id年份(生日))爲年份欄的值,對於月份和日期欄爲相同的值。mysql - 更新外鍵值

如何在MySQL中執行此操作?

我想這個解決方案:

update member set year=(select All_years.id from All_years,member where All_years.fromY=year(member.birthdate)) where id=30471; 

但它的原因 「ERROR 1093(HY000):您不能指定目標表 '成員' 在更新FROM子句」

在此先感謝

回答

0

你不想從子查詢中members表中選擇。改用你正在更新的表。

UPDATE member 
SET year=(
    SELECT id FROM all_years 
    WHERE fromY=year(member.birthdate) 
) 
WHERE id=30471; 

雖然年/月/日是外鍵的原因嗎?

+0

是的,因爲這些年顯示在我的系統 – Neveen 2009-10-19 07:51:20

+0

下拉列表,它會導致錯誤「無法添加或更新子行:外鍵約束失敗('CMMS/member',CONSTRAINT'member_ibfk_9' FOREIGN KEY(' year')參考'All_years_tmp'('id')ON DELETE CASCADE) 「如何可以強制更新? – Neveen 2009-10-19 07:55:13

+0

'year'列引用'all_years_tmp',而不是'all_years'。要獲得下拉菜單的年份列表,您可以使用'SELECT DISTINCT year(birthday)FROM members',而不需要維護一個單獨的表。 – 2009-10-19 08:11:19

-1
SELECT birthdate FROM member INTO @myBirthdate; 

update member set year=(select All_years.id from All_years,member where All_years.fromY=year(@myBirthdate)) where id=30471; 

相同的月份和日期。

+0

它會導致相同的錯誤「錯誤1093(HY000):您無法指定目標表'member'在FROM子句中更新」 – Neveen 2009-10-19 07:53:22