[英]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.