[英]MySQL query, finding from one table and insert into second table
I am looking for the following: 我正在寻找以下内容:
Need the row with this condition: Common values of Device columns AND first three chars of Interface column from both tables. 需要具有以下条件的行:设备列的公共值和两个表中的接口列的前三个字符。
Then the row which matched the above condition from Table1, retrieve the value of Specified column and store it in the Avgin column of the Table2 in the row where above condition matched. 然后,与Table1匹配上述条件的行检索Specified列的值,并将其存储在上述条件匹配的行中Table2的Avgin列中。
Can someone help me with it? 有人可以帮我吗? Database is MySQL. 数据库是MySQL。
If there are more than one matches, only the first one will be used. 如果有多个匹配项,则仅使用第一个匹配项。 If there are none, null will be used. 如果没有,则使用null。 If you would like something else, use ifnull()
. 如果你想要别的东西,请使用ifnull()
。
UPDATE
table2
SET
avgin=ifnull(
(
SELECT
Specified
FROM
table1
WHERE
table1.Device=table2.Device
AND substring(table1.Interface,1,3)=substring(table2.Interface,1,3)
LIMIT 1
),
'default value'
)
edit : added the ifnull()
编辑 :添加了ifnull()
UPDATE
with JOIN
is what you need here, something like this: 使用JOIN
UPDATE
是你需要的,如下所示:
UPDATE Table2 AS t2
INNER JOIN table1 AS t1 ON LEFT(t2.Interface, 3) = LEFT(t1.Interface, 3)
AND t1.Device = t2.Device
SET t2.Avgin = t1.specified;
With the JOIN
condition, as you explained in your question: 有了JOIN
条件,正如您在问题中所解释的那样:
LEFT(t2.Interface, 3) = LEFT(t1.Interface, 3)
AND
t1.Device = t2.Device
LEFT
will give you the first 3 chars from the left of both table. LEFT
将为您提供两张桌子左边的前3个字符。
See it in action here: 在这里看到它:
This will make the table2
looks like: 这将使table2
看起来像:
| CID | DEVICE | INTERFACE | AVGIN |
---------------------------------------------------
| HDC-HKG-R01 | HDC-TBONE-P1 | P09/0/0 | 121.36 |
| OCB-OCD-R01 | OCB-PE1 | Gi5/2 | 0.17 |
| HDC-BSA-R01 | HDC-TBONE-P1 | Se9/2/0 | (null) |
Use this to confirm you're getting the rows you're expecting (ie BEFORE updating anything): 使用它来确认您正在获得您期望的行(即在更新任何内容之前 ):
SELECT
t1.Specified
FROM
table2 t2
INNER JOIN table1 t1
ON t1.device = t2.device
AND LEFT(t1.interface,3) = LEFT(t2.interface,3)
And then, assuming that's right: 然后,假设是对的:
UPDATE table2 t2
INNER JOIN table1 t1
ON t1.device = t2.device
AND LEFT(t1.interface,3) = LEFT(t2.interface,3)
SET t2.Avgin = ifnull(t1.specified,'Default Value For When t1.Specified is NULL')
Note we're using an INNER join... that means that rows from table2 that have no corresponding row in table1, are discarded from the results (which is what you want). 注意我们正在使用INNER连接...这意味着table2中没有table1中相应行的行将从结果中丢弃(这是您想要的)。
The IFNULL
will allow you to use a default value in the case when your join succeeds (because device
and first three chars of interface
are common to both tables), but table1.specified
has a NULL value for that row. 当连接成功时, IFNULL
将允许您使用默认值(因为device
和interface
前三个字符对两个表都是通用的),但table1.specified
对该行具有NULL值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.