我正在尝试为table2中的select的每个响应复制行table1,并将其中一列的值更改为table2的结果
所以这是我从table1中选择我要复制的值:
SELECT DISTINCT * FROM table1 WHERE CODE = 'abcd'
响应:
Code zone
abcd 1
abcd 2
abcd 3
abcd 4
我希望上面选择的所有结果都可以复制到下面选择的每个回复中
SELECT DISTINCT CODE AS code
FROM table2
WHERE CODE LIKE '%abcd%'
目标:
Code zone
abcde 1
abcde 2
abcde 3
abcde 4
abcdef 1
abcdef 2
abcdef 3
abcdef 4
zabcd 1
zabcd 2
zabcd 3
zabcd 4
然后我想将这些值添加到table1
答案 0 :(得分:2)
听起来你想要CROSS JOIN
:
SELECT B.code, A.zone
FROM (SELECT DISTINCT Code, zone
FROM table1
WHERE CODE = 'abcd') A
CROSS JOIN (SELECT DISTINCT CODE AS code
FROM table2
WHERE CODE LIKE '%abcd%') B
;
如果您想在table1
中插入此数据:
INSERT INTO table1(code, zone)
SELECT B.code, A.zone
FROM (SELECT DISTINCT Code, zone
FROM table1
WHERE CODE = 'abcd') A
CROSS JOIN (SELECT DISTINCT CODE AS code
FROM table2
WHERE CODE LIKE '%abcd%') B
WHERE NOT EXISTS(SELECT 1 FROM table1
WHERE code = B.code
AND zone = A.zone)
;