【问题标题】:For all entries in one table, add to another table对于一个表中的所有条目,添加到另一个表
【发布时间】:2020-11-18 22:36:41
【问题描述】:

数据库如下所示:

表1

id   | name
1    | James
2    | Rick
3    | Carl

表2

id   | age | gender
<this table is empty>

我想做一个查询,将所有 ID 的相同数据传递到 table2。因此,查询后数据库将如下所示:

表1

id   | name
1    | James
2    | Rick
3    | Carl

表2

id   | age | gender
1    | 20  | male
2    | 20  | male
3    | 20  | male

我尝试进行一些 INNER JOIN 查询,但我似乎无法使其工作。有什么建议吗?

【问题讨论】:

  • 年龄 = 20 和性别 = 男性的数据来​​源是什么?
  • @TimBiegeleisen 我只是在做一个随机的例子。我需要固定这些值,实际上它与这个数据库结构无关,这只是我说明我想做的最简单的方法。答案很到位!

标签: mysql sql database select sql-insert


【解决方案1】:

您似乎想要来自table1ids,然后是其他列的固定值。

如果是这样,请考虑insert ... select 语法:

insert into table2 (id, age, gender)
select id, 20, 'male' from table1

【讨论】:

    【解决方案2】:

    你想要这个吗?

    insert into table2 (id, age, gender)
        select id, 20, 'male'
        from table1;
    

    通常,ids 是自动定义的,因此您可以忽略它:

    insert into table2 (age, gender)
        select 20, 'male'
        from table1;
    

    【讨论】:

    • 这就是答案
    【解决方案3】:

    你可以像这里描述的那样做:

    https://www.w3schools.com/sql/sql_insert_into_select.asp

    可能是这样的

    INSERT INTO table2 (id, age, gender)
    SELECT id,
           20,
           'male'
    FROM table1
    WHERE 1 = 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 2020-11-13
      • 2015-04-24
      • 1970-01-01
      相关资源
      最近更新 更多