【问题标题】:Insert records sql插入记录sql
【发布时间】:2016-12-14 10:35:08
【问题描述】:

有多个记录

例如:

   ID Name subject   cindex
    1   abc   mat      45
    2   jjj   scie     45
    3   kkk   geom     45  
    4   sdf   eng      45
    5   idf   law      45

现在我想插入相同的记录,但使用不同的cindex。我试过这个:

insert into b_table (ID,name,subject,cindex) values (+1,NULL,NULL,90)
select name,subject from b_table where cindex=45 

这里的ID 不是自动增量列。我尝试使用 +1 .. 现在我认为此查询不正确,那么如何选择记录并插入具有不同 cindex 的相同记录?

【问题讨论】:

  • 如果已经有1、2、3再加1,插入会尝试插入2、3、4。即重复的 id 值!
  • 告诉我们您遇到的错误
  • 不想插入不同的 cindex 和明显不同的 ID ..
  • 在mysql中你可以创建字段A_I,在ORACLE中你必须在Table insert上定义一个触发器。
  • 您使用的是哪个 DBMS?

标签: sql select insert


【解决方案1】:

有一个返回表的最大 id 的子查询。将该值添加到每个选定的 id。

insert into b_table (ID,name,subject,cindex)
  select id + (select max(id) from b_table), Name, subject, 90
  from b_table where cindex = 45

【讨论】:

  • 复杂:/ .. 我不明白为什么你从表中选择 90 作为 cindex,因为表中没有 cindex 90 的记录?
  • 你不想插入 cindex 90 而不是 45 吗?
  • 在这里插入 SELECT 返回的内容。如果您选择 90,则将插入该值!
  • 但仍然不明白为什么我们在 select 语句中选择 90 .. 为什么不在 insert 语句中。我们插入 90 不选择
  • 请澄清这一点.. @jarih
【解决方案2】:

如果 ID 列是 autoincrement ,请不要插入任何内容,请使用:

insert into b_table (id,name,subject,cindex)
select (SELECT max(id) FROM b_table) + id,name,subject,90 from b_table where cindex=45 

编辑:为了澄清您在 cmets 中提出的问题,以这张表为例:

ID, NAME
1    super
2    sagi
3    josh

SELECT id, name , 'bla bla bla' as constant_string, 45 constant_number
FROM Table

将输出以下内容:

ID,name,constant_string,constant_number
1  super    'bla bla bla'   45
2  sagi     'bla bla bla'   45
3  josh     'bla bla bla'   45

当您选择一个字符串或一个数字时,它们不是从实际的表数据中选择的。它们被生成为“附加”到您的数据的常量值。

【讨论】:

  • "ID 不是自动递增的"。
  • 出于某种原因,我将其读作“ID 是自动增量”:) @jarlh
  • 但是表中没有 90 cindex 那么我如何选择 90?
  • 是的 id 不是自动增量想用 +1 来做这件事 .. 像 id +1 ??
  • 高声誉并不意味着你不能帮助某人@ubaidashraf
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多