4

我必须使用以下模式将数据插入到表中

INSERT INTO tablename (a, b) VALUES (
    (123, (SELECT foo FROM someothertable WHERE some_condition)),
    (456, (SELECT foo FROM someothertable WHERE some_condition)),
    (789, (SELECT foo FROM someothertable WHERE some_condition)),
    ...

所有插入的行都具有相同的b列值,我想将其分解。我可以手动执行子选择并将值粘贴到其中,但这会破坏我正在编写的脚本集中的封装。

我可以在同一个查询中用纯 SQL 执行此操作吗?

4

5 回答 5

3
INSERT INTO tablename (a, b)
SELECT X.bar, S.foo
FROM someothertable S
   CROSS JOIN
   (SELECT 123 AS bar UNION ALL SELECT 456 UNION ALL SELECT 789) X
WHERE some_condition
于 2012-02-14T13:15:32.617 回答
2

使用该值声明一个变量并在插入时使用它。

假设foo是 `varchar(10) 它会是这样的:

declare @toInsert varchar(10)

select @toInsert = foo FROM someothertable WHERE some_condition

INSERT INTO tablename (a, b) VALUES (
    (123, @toInsert),
    (456, @toInsert),
    (789, @toInsert),
于 2012-02-14T13:14:35.057 回答
1
INSERT INTO tablename (a, b) 
  SELECT a, b
  FROM
      ( SELECT 123 AS a UNION
        SELECT 456 UNION
        ...  
        SELECT 789 
      ) AS aa
    CROSS JOIN 
      ( SELECT foo AS b FROM someothertable WHERE some_condition ) AS bb
于 2012-02-14T13:15:03.047 回答
0

这就是我的意思:

create table tableName (
a varchar(50),
b varchar(50))

create table someothertable (
keyToTableName varchar(50),
someOtherA varchar(50))

insert into someothertable values('a', 'otherA')
insert into someothertable values('b', 'otherB')

insert into tableName
select 'a', someOtherA from someothertable where keyToTableName='a' UNION
select 'b', someOtherA from someothertable where keyToTableName='b' 
于 2012-02-14T13:07:21.750 回答
0

这里有两种方法,这两种方法都避免重复子选择,但不是严格的“在一个查询中”:

1)使用临时变量

SET @b = SELECT foo FROM someothertable WHERE somecondition;
INSERT INTO tablename(a, b) VALUES (
  (1, @b),
  (2, @b),
  ...

2)insert用于设置列a,然后用于update设置列b。这可以暂存到一个临时表。

CREATE TEMPORARY TABLE tmp LIKE tablename;
insert into tmp(a) values (1),(2),...
update tmp set b = select foo from someothertable where some_condition;
insert into tablename(a,b) select * from tmp;
于 2012-02-14T13:30:10.607 回答