当前位置: 动力学知识库 > 问答 > 编程问答 >

sql - Multiple Updates with table comparison in MySQL

问题描述:

I couldn't figure out how to make multiple updates with one single query.

Here is my 2 tables.

devices_table

DeviceID Brand SerialNumber

---------------------------------

1 Nintendo 324234324

2 Nintendo 89978333

3 Sony Z3432343

4 Sony Z3424335

temporary_table

DeviceID Brand SerialNumber

---------------------------------

NULL Nintendo 324234324

NULL Nintendo 89978333

NULL Sony Z3432343

NULL Sony Z3424335

How I'll fill the DeviceID in temporary_table? What kind of query I do need?

网友答案:

You need to use an update statement:

UPDATE  temporary_table
SET     DeviceID = (    SELECT  Devices_table.DeviceID
                        FROM    Devices_table
                        WHERE   Devices_table.Brand = temporary_table.Brand
                        AND     Devices_table.SerialNumber = temporary_table.SerialNumber
                    );

Example on SQL Fiddle

Or you can use a join rather than a correlated subquery:

UPDATE  temporary_table
        INNER JOIN Devices_table
            ON Devices_table.Brand = temporary_table.Brand
            AND Devices_table.SerialNumber = temporary_table.SerialNumber
SET     temporary_table.DeviceID = Devices_table.DeviceID;

Example on SQL Fiddle

网友答案:

Yes u can use the below query:

UPDATE  temporary_table
SET     DeviceID = Devices_table.DeviceID
FROM    temporary_table
INNER JOIN Devices_table
ON Devices_table.Brand = temporary_table.Brand
AND Devices_table.SerialNumber = temporary_table.SerialNumber;
分享给朋友:
您可能感兴趣的文章:
随机阅读: