下面的示例如何在SQL中编写代码

时间:2019-07-27 20:47:53

标签: mysql sql

我有两个表BOQ和DPR

表格:BOQ

ID | Buidling| Activity |Plan_Start_Date|Actual_Start_Date
1  |A-1      |Shuttering|02-02-2019     |15-02-2019
2  |A-2      |Shuttering|13-02-2019     |13-02-2019

表格:DPR

ID | Buidling| Activity |Date          |
1  |A-1      |Shuttering|15-02-2019    |

我需要为列Actual_Start_Date写一个表达式,以便当两个表中的BuildingActivity列都匹配时,它应该在DPR表中将日期显示为{{1} }(在上述情况下,由于表格和活动列已匹配,因此15-02-2019是BOQ中ID 1的Actual_Start_Date)。 如果没有匹配的值,则Actual_Start_Date应显示Actual_Start_Date,如BOQ的ID 2

1 个答案:

答案 0 :(得分:0)

您想要一个left join

select . . .,  -- whatever other columns you want
       coalesce(dpr.date, boq.actual_start_date) as actual_start_date
from boq left join
     dpr
     on boq.building = dpr.building and
        boq.activity = dpr.activity;

您可以轻松地将其变成update

update boq join
       dpr
       on boq.building = dpr.building and
          boq.activity = dpr.activity
    set boq.actual_start_date = coalesce(dpr.date, boq.actual_start_date) ;