Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert values into a table, using a subquery with more than one result?

I really would appreciate your help.

Probably it's a quite simple problem to solve - but I'm not the one .. ;-)

I have two tables in SQL Server:

  1. article
  2. prices

Now I want to select a certain set of ids and insert some entries into the prices-table with those ID.

e.g. (wrong and not working SQL)

INSERT INTO prices (group, id, price) 
VALUES (7, (select articleId from article WHERE name LIKE 'ABC%'), 1.50);

SQL Error -> subquery has more than 1 value

thanks for help

like image 286
Futuretec Avatar asked Oct 07 '22 01:10

Futuretec


People also ask

How do you write a subquery in insert statement?

Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions. The basic syntax is as follows.

How many values can a subquery return if it is used in an insert statement?

A single-row subquery can return a maximum of one value. Multiple-column subqueries return more than one column to the outer query.

Can subquery return more than one value?

Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).

Can we insert multiple values in a table with a single query?

Answer. Yes, instead of inserting each row in a separate INSERT statement, you can actually insert multiple rows in a single statement. To do this, you can list the values for each row separated by commas, following the VALUES clause of the statement.


2 Answers

You want:

insert into prices (group, id, price)
select 
    7, articleId, 1.50
from article where name like 'ABC%';

where you just hardcode the constant fields.

like image 166
Mike Ryan Avatar answered Oct 15 '22 15:10

Mike Ryan


Try this:

INSERT INTO prices (
    group, 
    id,
    price
) 
SELECT
    7,
    articleId,
    1.50
FROM
    article 
WHERE 
    name LIKE 'ABC%';
like image 28
Stefan H Avatar answered Oct 15 '22 17:10

Stefan H