简体   繁体   中英

SQL insert by select from another table

I have a table X in which I want to insert a row. This table has a reference to a foreign key from another table Y. I would now like to use this id from table Y to be inserted into table X when I insert a new entry in table X.

INSERT into X (col1, col2, col3, foreignKey)
(
  'col1 value',
  'col2 value',
  'col3 value',
  select id from Y y where y.id = '2'
);

This fails for the obvious reason that the sql is not well formed. How to get around this?

Depends on what you want to do:

INSERT into X (col1, col2, col3, foreignKey)
select
  'col1 value',
  'col2 value',
  'col3 value',
  id from Y y where y.id = '2';

Will insert the same number of rows as the y where y.id = '2' returns.

Or:

INSERT into X (col1, col2, col3, foreignKey)
(
  'col1 value',
  'col2 value',
  'col3 value',
  (select id from Y y where y.id = '2')
);

Does only work if (select id from Y y where y.id = '2') returns 1 row (or 0 rows.) Will always insert 1 row, even if y is empty!

The correct syntax for this is this:

Insert Into X (Col1, Col2, Col3, ForeignKey)
Select  'col1 value',
        'col2 value',
        'col3 value',
        id
From    Y y
Where   y.Id = '2'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM