如何从一个 table 列中获取值,将它们与字符串连接并插入到另一个 table 中?

How to get values from one table column, concatenate them with a string and insert them in another table?

如何:

  1. 从 table1.column1 获取值(例如 abc)

    table1.column1=abc

  2. 将它们与某些固定字符串连接起来,例如

    xxx yyy zzz

  3. 将结果作为单独的行插入 table2.column2 中。最终结果应该是具有如下值的行:

    table2.column2=abc_xxx table2.column2=abc_yyy table2.column2=abc_zzz

(table2 有一个连接列,指示 table2.column2 记录对应的 ID,以防万一)

  1. table1.column1 中具有 table1.item_id > 100
  2. 的所有记录重复此过程

编辑:为了方便起见,我希望最终结果行序列看起来像:

source1_xxx source1_yyy source1_zzz source2_xxx source2_yyy source2_zzz

不喜欢:

source1_xxx source2_xxx source1_yyy source2_yyy source1_zzz source2_zzz

正在修改答案。

归功于 StuartLC ..他是对的,您需要使用交叉连接

INSERT INTO Table2(column2)
SELECT CONCAT(t1.column1, '_', x.col)
FROM Table1 t1
CROSS JOIN 
(SELECT 'xxx' AS col
 UNION
 SELECT 'yyy'
 UNION 
 SELECT 'zzz') x;

这是你想要的吗

 insert into table2(column2)
 select concat(col1,'_','xxx') from table1
 union

 select concat(1col1,'_','yyy') from table1

union 

 select concat(col1,'_','zzz') from table1

否则将整个 select 语句保留在视图中并在插入语句中使用它

create view abc 
as
 select concat(col1,'_','xxx') from table1
     union

     select concat(1col1,'_','yyy') from table1

    union 

     select concat(col1,'_','zzz') from table1

然后

  insert into table2(column2) select * from abc

如果我没理解错的话,您需要为 Table1 中的每个现有行添加 N(例如 3)个条目。如果是这样,您可以 CROSS JOIN Table1 到值的投影,如下所示:

INSERT INTO Table2(column2)
    SELECT CONCAT(t1.column1, '_', x.col)
    FROM Table1 t1
    CROSS JOIN 
    (SELECT 'xxx' AS col
     UNION
     SELECT 'yyy'
     UNION 
     SELECT 'zzz') x;

SqlFiddle here

编辑

查询已更新为也了解排序和过滤要求:

INSERT INTO Table2(column2)
    SELECT CONCAT(t1.column1, '_', x.col)
    FROM Table1 t1
    CROSS JOIN 
    (SELECT 'xxx' AS col
     UNION
     SELECT 'yyy'
     UNION 
     SELECT 'zzz') x
    WHERE t1.ID > 100
    ORDER BY t1.column1 ASC, x.col ASC;

With an updated SqlFiddle