【问题标题】:SQL - Insert two columns, one from a table, the other constantSQL - 插入两列,一列来自表,另一列是常量
【发布时间】:2019-05-17 19:28:14
【问题描述】:

我有一个多对多关系表,我需要在其中插入行。

假设标题是:

Table1: Id_1 | Etc....
Table2: Id_2 | Etc....
Relation_Table: Id_1 | Id_2 | Etc.

我需要做以下事情:

  • 在表 1 中插入一个新元素
  • 将此新元素链接到表 2 中的所有元素

所以,我需要在关系表中添加n行如下:

(id_1_new, id_2_0),
(id_1_new, id_2_1),
(id_1_new, id_2_2),
(id_1_new, id_2_3),
(id_1_new, id_2_4),
(id_1_new, id_2_5),
(id_1_new, id_2_6),....
  • id_1_new 是已知的,可以手动输入
  • id_2_n 可能来自select Id_2 from Table2

如何使用 SQL 语句做到这一点? Microsoft Access 解决方案也受到欢迎。

【问题讨论】:

  • “新元素”是什么意思——新字段还是新记录?在 VBA 中使用循环代码添加 n 条记录。 stackoverflow.com/questions/41817502/…
  • @June7 “新元素”是新纪录
  • 好的,将新记录提交到表中,然后运行使用该新 ID 创建相关依赖记录的代码。链接中的示例代码。尝试,当您有特定问题的代码时,发布问题。
  • 为什么不INSERT INTO table1 (Id_1, Id_2) SELECT constant_value, Id_2 FROM table2

标签: sql ms-access sql-insert


【解决方案1】:

您可以使用insert... select 语法从第二个表中选择数据到您的关系表中,在选择中使用新的 id 作为 const:

insert into Relation_table (Id_1, Id_2) 
   select 'id_1_new' as Id_1, Id_2 from Table2;

【讨论】:

  • 这太令人困惑了,但它确实有效......我想它就像select (('id_1_new' as Id_1),(Id_2 from Table2)),这是正确的吗?我可以尝试(当然结果不同)select Id_1 from Table1, Id_2 from Table2 之类的东西吗?
  • @DanielMöller 可以这样想——您运行选择查询,并将结果插入到您的关系表中。所以只要选择部分有效,并返回预期的列以适应插入,它就会起作用
猜你喜欢
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
相关资源
最近更新 更多