Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Subquery in Select Query

Tags:

mysql

I have a "Groups" table and a "Participants" table. Now I need to insert one Participant for each Group. How would I automate this?

INSERT INTO "Participants" ("Name", "FirstName", "GroupID") VALUES ("GENERIC", "GENERIC", GroupID)

This Insert should be called for each Group in the Groups table, and the "GroupID" replaced with the corresponding ID.

Would this work with a subquery?

Thanks, martin

like image 341
Martin Avatar asked Aug 20 '09 08:08

Martin


People also ask

Can we use subquery in select clause?

You can use subqueries in SELECT, INSERT, UPDATE, and DELETE statements wherever expressions are allowed. For instance, you can use a subquery as one of the column expressions in a SELECT list or as a table expression in the FROM clause. A DML statement that includes a subquery is referred to as the outer query.

How does a subquery in an SQL select statement is enclosed in?

a subquery must be enclosed in the parenthesis.

When you insert a select statement into a FROM clause it becomes a subquery?

When you put a select statement into a FROM clause, it becomes a subquery. The subquery returns a temporary table in database server's memory and then it is used by the outer query for further processing.


2 Answers

INSERT INTO SELECT...

INSERT INTO
    Participants
(
    Name,
    FirstName,
    GroupID
)
SELECT
    'GENERIC',
    'GENERIC',
    GroupID
FROM
    Groups
like image 189
Robin Day Avatar answered Sep 20 '22 19:09

Robin Day


INSERT INTO `Participants`
SELECT ("Name", "FirstName", `group_id`)
FROM `Group`
like image 34
Zed Avatar answered Sep 18 '22 19:09

Zed