将数据从自身和另一个表mysql插入表中

时间:2015-02-26 02:29:43

标签: mysql database

我有两张桌子:

table1包含roleid

table2包含stringtexttable1_roleid(这是表1中roleid字段的FK)

table2现在包含5个条目,每个条目具有相同的table1_roleid值和不同的stringtext值,我想在同一个表中复制stringtext值,但是我想从table1_roleid获取的table1值不同。

在此处进一步解释:

table1
+--------+
| Roleid |
+--------+
| 1      |
| 2      |
| 3      |
+--------+

table2
+------------+---------------+
| stringtext | table1_roleid |
+------------+---------------+
| text1      |             1 |
| text2      |             1 |
| text3      |             1 |
| text4      |             1 |
| text5      |             1 |
+------------+---------------+

table2的最终结果应为:

table2
+------------+---------------+
| stringtext | table1_roleid |
+------------+---------------+
| text1      |             1 |
| text2      |             1 |
| text3      |             1 |
| text4      |             1 |
| text5      |             1 |
| text1      |             2 |
| text2      |             2 |
| text3      |             2 |
| text4      |             2 |
| text5      |             2 |
| text1      |             3 |
| text2      |             3 |
| text3      |             3 |
| text4      |             3 |
| text5      |             3 |
+------------+---------------+

我想创建一个复制table2的临时表,每次我都可以更新临时表中的table1_roleid,但是我可以在一个更聪明的方法之后我可以放入一个循环示例并插入到同一个表中而没有临时表。

2 个答案:

答案 0 :(得分:1)

您可以使用cross join生成所需的所有行。由于结果已包含table2中的某些行,因此您需要将其过滤掉。这是一种方式:

insert into table2(string_text, table1_roleid)
    select t2.string_text, t1.roleid
    from table2 t2 cross join
         table1 t1
    where t1.roleid <> 1;

更通用的方法是将where子句更改为:

    where not exists (select 1
                      from table tt2
                      where tt2.string_text = t2.string_text and
                            tt2.table1_roleid = t1.roleid
                     )

答案 1 :(得分:0)

另一种方法是在两个表之间创建一个笛卡尔计划。与cross join

相同
Insert into table2 (string_text, table1_roleid)
  select t2.stringtext, t1.Roleid 
    from table1 t1,
         table2 t2
   where t1.Roleid <> 1

请在此处查看:http://sqlfiddle.com/#!2/d7fc3/1

它所做的是组合指定表中的每个注册表,除了(或仅限)那些符合条件的注册表。

相关问题