如何使用另一个表中的值更新字段值

时间:2017-08-07 16:56:50

标签: mysql

我有四个候选名称,program_type,program_of_interest和desired_intake。候选表与三个表中的其余表具有多对一关系。

候选表如下所示: enter image description here

program_type表: enter image description here

program_of_interest表: enter image description here

desired_intake表: enter image description here

我正在尝试将候选表中的program_type,program_of_interest,desired_intake id替换为各自表中的相应值。 我可以在此线程SQL Replace multiple variables from another table in query result的帮助下根据需要选择值。以下是我选择的解决方案:

SELECT 
     c.id, 
     p.value as 'Program type', 
     p1.value as 'Program of interest',
     d.value as 'Desired intake'
FROM candidate c
JOIN program_type p on p.id = c.program_type
JOIN program_of_interest p1 on p1.id = c.program_of_interest
JOIN desired_intake d on d.id = c.desired_intake

我的问题是如何将候选表中的ID替换为各自的值?

1 个答案:

答案 0 :(得分:1)

您可以在加入时使用更新根据

  Update candidate c
  INNER JOIN program_type p on p.id = c.program_type
  INNER JOIN program_of_interest p1 on p1.id = c.program_of_interest
  INNER JOIN desired_intake d on d.id = c.desired_intake
    set c.program_type = p.value,
        c.program_of_interest = p1.value,
        c.desired_intake  = d.value

但似乎很奇怪你想要更新例如:program_type的值(c.program_type = p.value) 并且您正在使用program_type进行连接(p.id = c.program_type)