我有以下表格:
T1 T2 T3 T4
ID ID A B C ID
--- -------- --- ---
1 3 u v w 3
2 4 x y z 4
首先,我必须从B中选择具有从C检索到的ID的项目:
SELECT a,b,c FROM T2 WHERE ID IN (SELECT ID FROM T3)
--will return u,v,w
x,y,z
现在我想检索T1中的ID并将它们与上面查询返回的每一行合并,并将它们插入到T4中:
1 u v w
1 x y z
2 u v w
2 x y z
答案 0 :(得分:2)
使用CROSS JOIN选项
INSERT T4(ID, A, B, C)
SELECT t1.ID, o.A, o.B, o.C
FROM T1 t1 CROSS JOIN (
SELECT a,b,c
FROM T2 t2 JOIN T3 t3 ON t2.ID = t3.ID
) o
SQLFiddle上的演示
答案 1 :(得分:0)
如果我理解正确,这可以提供帮助:
INSERT INTO T4
SELECT ID, A, B, C
FROM (SELECT a,b,c FROM T2 WHERE ID IN (SELECT ID FROM T3)) tab1
CROSS JOIN T1