从单个insert和select语句中插入多行

时间:2015-10-01 05:58:32

标签: mysql

我有一张桌子和一张桌子

Table d
--------

id number
1   23
1   24
1   25
2   22
2   23

我需要插入表格f

INSERT INTO f 
 SELECT max(f)+1,
 (select d.number from d where number = 1),
 FROM f

表f需要

id   d.id      d.number
1     1         23
2     1         24
3     1         25

我必须选择3行并使用一个选择查询插入到该表中。

3 个答案:

答案 0 :(得分:2)

您可以使用以下sql查询,

{{1}}

答案 1 :(得分:0)

您只需在子查询和外部查询中指定正确的列名。

INSERT INTO f VALUES (id,number) (SELECT id,number FROM d WHERE id = 1)

并且您无法在f idnumber中将dd.id中的d.numberINSERT INTO f VALUES ( id, idNew, number ) SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowNumber, d.id, d.number FROM d WHERE id = 1 称为外键可以&#39 ; t设置在非主键列上。

答案 2 :(得分:0)

首先,让我们设置您的表格定义:http://sqlfiddle.com/#!6/6b644c/1

create table d (id int, num int);
create table f (id int, d_id int, d_num int);

insert into d (id, num) values
(1,23),
(1,24),
(1,25),
(2,22),
(2,23);

然后,这应该可以获得您指定的结果。

insert into f (id, d_id, d_num) 
  select row_number() over (order by num), d.id, d.num
  from d
  where d.id = 1;

如果您想为每个现有的id计数器启动新的partition by计数器,请添加where子句并将insert into f (id, d_id, d_num) select row_number() over (partition by id order by num), d.id, d.num from d 这样的内容保留为:var dir = process.env.PWD; options["fName"] = "./test.apk"; {3}}

SELECT A.[CallID]
FROM dbo.[Calls] A WITH(NOLOCK)
INNER JOIN [dbo].[Issues] B WITH(NOLOCK) ON A.[CallID] = B.[CallID]
WHERE A.[AddedByUserID] = @UserID
  AND A.[EndTime] IS NULL
  AND DATEDIFF(d,A.AddedOn,GETDATE()) <= 1