简体   繁体   English

mysql-用值更新外键

[英]mysql - update foreign key with a value

I have a birthdate, year, month, day columns where columns "year,month,day" are foreign key to other tables What I want to do is for each birthdate get id(year(birthdate)) to be the value of year column and the same thing for month and day columns. 我有一个生日日期,年,月,日列,其中“年,月,日”列是其他表的外键。我要为每个生日设置id(year(birthdate))作为年列的值对于月和日列也是如此。

How can I do this in MySQL? 如何在MySQL中做到这一点?

i tried this solution: 我试过这个解决方案:

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

but it cause " ERROR 1093 (HY000): You can't specify target table 'member' for update in FROM clause " 但它会导致“错误1093(HY000):您无法在FROM子句中指定目标表'member'进行更新”

Thanks in advance 提前致谢

You don't want to select from the members table in the subquery. 您不想从子查询的members表中进行选择。 Use the table you are updating instead. 请改用您要更新的表。

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

Is there a reason why year/month/date are foreign keys though? 为什么年/月/日是外键?

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;

same goes for month and day. 一个月和一天都一样。

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

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