Tony77
Tony77

Reputation: 311

Mysql select from a table and insert into another

I have a mysql table called jos_users_quizzes with the following columns:

id
quiz_id
user_id

I have a second table called  jos_users with this columns


id 
name
username
department

the user_id on first table is linked with the id of second table so quiz_id = id (jos_users)

How can build a query to multiple insert the ids of a selected department into the jos_users_quizzes table... in one click

I am thinking meabe a sub query or a loop, but no sure how.

Thanks in advance!

Upvotes: 0

Views: 2515

Answers (2)

Joel Hudon
Joel Hudon

Reputation: 3215

With INSERT ... SELECT, you can quickly insert many rows into a table from one or many tables. For example

INSERT INTO jos_users_quizzes (quiz_id)
  SELECT jos_users.id
  FROM jos_users WHERE jos_users.department = 100;

Upvotes: 0

The Scrum Meister
The Scrum Meister

Reputation: 30111

INSERT jos_users_quizzes (quiz_id, user_id)
SELECT $quizID, id
FROM jos_users
WHERE department = 'selected department'

Upvotes: 4

Related Questions