2016-07-14 115 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