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

时间:2015-04-06 08:27:10

标签: mysql sql percona

如何:

  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

  4. (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

3 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要表1中每个现有行的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

答案 1 :(得分:0)

修改答案。

归功于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;

答案 2 :(得分:0)

这就是你想要的

 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语句并在insert语句中使用它

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