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

その値で変数を宣言し、インサートで使用します。

` varchar foo(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

ここに2つの方法があります。どちらも副選択の繰り返しを避けますが、厳密には「1つのクエリ」ではありません。

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 に答える