茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1729867 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
IMG_0054.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

DB研討會 : [轉貼]如何更新資料表欄位透過其他資料表(UPDATE FROM TABLE)

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15773
[轉貼]mysql update column with value from another table
mysql update column with value from another table

I have two tables, both looking like
id  name  value
===================
1   Joe     22
2   Derk    30

I need to copy the value of value from tableA to tableB based on check name in each table.

Any tips for this UPDATE statement?



In addition to this answer if you need to change t1.value according to t2.value dynamically you can do for example:
UPDATE tableB
INNER JOIN tableA ON tableB.name = tableA.name
SET tableB.value = IF(tableA.value > 0, tableA.value, tableB.value)
WHERE tableA.name = 'Joe'




you need to join the two tables:

for instance you want to copy the value of name from tableA into tableB where they have the same ID
UPDATE tableB t1
        INNER JOIN tableA t2
             ON t1.id = t2.id
SET t1.name = t2.name
WHERE t2.name = 'Joe'

UPDATE 1
UPDATE tableB t1
        INNER JOIN tableA t2
             ON t1.id = t2.id
SET t1.name = t2.name

UPDATE 2
UPDATE tableB t1
        INNER JOIN tableA t2
             ON t1.name = t2.name
SET t1.value = t2.value




Second possibility is,
UPDATE TableB
SET TableB.value = (
    SELECT TableA.value
    FROM TableA
    WHERE TableA.name = TableB.name
);


原文出處:sql - mysql update column with value from another table - Stack Overflow
前一個主題 | 下一個主題 | | | |

討論串




Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|