我有两个表,一个是值,另一个是用户。
我想将Table_1.value
更新为a
我Table_1.date < user_table.date
的给定user_id
。
Table_1
|user_id | value | date |
|--------|-------|------------|
| 1 | f | 2013-12-11 |
|--------|-------|------------|
| 2 | k | 2013-12-05 |
|--------|-------|------------|
| 3 | l | 2013-12-01 |
|--------|-------|------------|
| 4 | n | 2013-11-09 |
|--------|-------|------------|
| 4 | a | 2012-10-11 |
|--------|-------|------------|
| 2 | v | 2013-11-07 |
|--------|-------|------------|
| 1 | o | 2013-12-10 |
|--------|-------|------------|
| 3 | p | 2013-11-15 |
user_table
|user_id | date |
|--------|------------|
| 1 | 2013-12-15 |
|--------|------------|
| 2 | 2013-11-03 |
|--------|------------|
| 3 | 2013-12-11 |
|--------|------------|
| 4 | 2013-12-09 |
答案 0 :(得分:2)
试试这个:
update table1 inner join user_table
on (table1.user_id = user_table.user_id
and table1.date < user_table.date)
set table1.value = 'a'
如果您想添加特定用户,请添加where table1.user_id = 1
或任何ID。
在小提琴上看到它:http://sqlfiddle.com/#!2/e0895/1
修改强>
随着要求的变化(另外一个表),它将是:
UPDATE table_1 inner join table_3
on (table_1.date = table_3.date)
inner join user_table on
(table1.user_id = user_table.user_id
and table1.date < user_table.date )
set table_1.value = table_3.value
答案 1 :(得分:0)
update Table_1,user_table
set value='a'
where Table_1.user_id = user_table.user_id
and Table_1.date < user_table.date