[英]Update a third table from two other tables
我有两个表,这些表的ID应基于“ orderID”进行匹配。
例如,Table1.ID = 1&orderid3。应该与Table2.ID = 2且orderid = 3匹配。
与这2个ID的关系存储在表3中,如下所述。
UPDATE table3
SET table1ID, table2ID =(
SELECT table1.1ID, table2.2ID
FROM table1 a
INNER JOIN table2 b
ON a.orderid = b.orderid
)
Table1 Table2 Table3
1ID, orderid 2ID, orderid 3ID, table1ID, table2ID
1 3 1 1 1 1 2
2 2 2 3 2 2 3
3 1 3 2 3 3 1
我正在尝试更新表3中的值为空的table1ID,但是不确定如何编写查询,以便仍然与之匹配。
Table1 Table2 Table3
1ID, orderid 2ID, orderid 3ID, table1ID, table2ID
1 3 1 1 1 2
2 2 2 3 2 3
3 1 3 2 3 3 1
这未经测试,但我认为应该可以。
标识符可以以数字开头,但除非加引号,否则不能仅由数字组成。
这个想法是从table1
和table2
检索匹配对,然后在table3.table1id IS NULL
情况table3
相应地更新table3.table1id IS NULL
以便没有值被覆盖。
UPDATE
table3 t
LEFT JOIN (
select x.`1ID`, y.`2ID`
from table1 x
inner join table2 y on x.orderid = y.orderid
) foo ON t.table2id = foo.`2ID`
SET
t.table1id = foo.`1ID`
WHERE
t.table1id IS NULL
附加SQLFiddle。 单击此处查看其工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.