我有一张这样的表:
----------------------------------
| id | date1 | date2 | type |
----------------------------------
| 1 | NULL | NULL | A |
| 1 | NULL | NULL | B |
| 1 | NULL | NULL | A |
| 1 | NULL | NULL | A |
| 1 | 2016-08-02 | NULL | C |
| 1 | NULL | NULL | B |
| 2 | NULL | NULL | A |
| 2 | NULL | NULL | A |
| 2 | NULL | NULL | A |
| 2 | NULL | NULL | B |
| 2 | 2016-08-15 | NULL | C |
| 2 | NULL | NULL | B |
----------------------------------
我希望通过单一查询成为:
----------------------------------------
| id | date1 | date2 | type |
----------------------------------------
| 1 | NULL | 2016-08-02 | A |
| 1 | NULL | 2016-08-02 | B |
| 1 | NULL | 2016-08-02 | A |
| 1 | NULL | 2016-08-02 | A |
| 1 | 2016-08-02 | NULL | C |
| 1 | NULL | 2016-08-02 | B |
| 2 | NULL | 2016-08-15 | A |
| 2 | NULL | 2016-08-15 | A |
| 2 | NULL | 2016-08-15 | A |
| 2 | NULL | 2016-08-15 | B |
| 2 | 2016-08-15 | NULL | C |
| 2 | NULL | 2016-08-15 | B |
----------------------------------------
获取的日期将始终为“C型”,要更新的字段将始终与日期的ID相同,并且“类型A”或“类型B”
有什么建议吗?
答案 0 :(得分:3)
您可以使用更新的联接子选择
update my_table
inner join ( select id, date1 from my_table where type ='C') t2
on my_table.id = t2.id
set date2 = t2.date1
where type in ('A','B')
答案 1 :(得分:2)
UPDATE myTable t1
SET date2 = (SELECT MAX(date1)
FROM myTable t2
WHERE t2.id = t1.id)
WHERE t1.type <> 'C'