SQLite - 根据其他两个表列的值更新列

时间:2016-07-14 18:48:05

标签: sqlite

我正在尝试将 Data1 ID 更新为 Record2 ID

  • Record1 Record2 名称是相同的,
  • 记录2
  • 重量更高。

记录1

| ID | Weight | Name |
|----|--------|------|
|  1 |     10 |    a |
|  2 |     10 |    b |
|  3 |     10 |    c |

RECORD2

| ID | Weight | Name |
|----|--------|------|
|  4 |     20 |    a |
|  5 |     20 |    b |
|  6 |     20 |    c |

数据1

| ID | Weight |
|----|--------|
|  4 |     40 |
|  5 |     40 |

我尝试过以下SQLite查询:

update data1
set id = 
  (select record2.id 
   from record2,record1 
   where record1.name=record2.name 
   and record1.weight<record2.weight)
where id in
  (select record1.id
   from record1, record2
   where record1.name=record2.name
   and record1.weight<record2.weight)

对于所有记录,使用上述查询 Data1 id 更新为4。

注意: Record1 ID Data1 的外键。

1 个答案:

答案 0 :(得分:1)

对于给定的数据集,以下似乎是原因:

update data1
set id = 
  (select record2.id 
  from record2,record1 
  where 
   data1.id = record1.id
   and record1.name=record2.name 
   and record1.weight<record2.weight)
where id in
  (select record1.id
  from record1, record2
  where
    record1.id in (select id from data1)
    and record1.name=record2.name 
    and record1.weight<record2.weight)
;

查看实际操作:SQL Fiddle

请评论是否需要调整/进一步详细说明。