2016-07-14 114 views
0

我试图更新数据1IDRECORD2ID时:SQLite的 - 更新基于值从其他两个表列列

  • 记录1的和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) 

使用上面的查询数据1ID更新为4的所有记录。

注:记录1ID数据1外键。

+0

@CL。这个问题使用三个表格,我无法使用您为此提供的相同查询。 – Prabha

+0

如果我编写查询的建议然后它不识别record1.name 更新DATA1 设定ID = (从RECORD2 其中record1.name = record2.name 和record1.weight Prabha

回答

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

请评论如果和因为这需要调整/进一步的细节。

+0

谢谢!它的工作方式完全如此。 @Abecee – Prabha

+0

@Prabha:请记住,如果您的备注“记录1的ID是Data1的外键”,这将会/应该/可能不会以这种方式工作。在模式级别执行。但是,这似乎并没有像[记录](https://www.sqlite.org/foreignkeys.html)那样工作 - 请参阅[SQL小提琴](http://sqlfiddle.com/#!5/c6926/1)。 – Abecee