带有公共select-from的SQL多重插入

时间:2012-02-14 13:04:52

标签: sql mysql5

我必须将数据插入到具有以下模式的表中

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列的相同值,我想将其考虑在内。我可以手动执行subselect并粘贴值,但这会打破我正在编写的脚本集中的封装。

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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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),

答案 2 :(得分: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

答案 3 :(得分: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' 

答案 4 :(得分: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;