Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert results of subquery into table with a constant

The outline of the tables in question are as follows:

I have a table, lets call it join, that has two columns, both foreign keys to other tables. Let's call the two columns userid and buildingid so join looks like

+--------------+
| join         |
|--------------|
|userid        |
|buildingid    |
+--------------+

I basically need to insert a bunch of rows into this table. Each user will be assigned to multiple buildings by having multiple entries in this table. So user 13 might be assigned to buildings 1, 2, and 3 by the following

13 1
13 2
13 3

I'm trying to figure out how to do this in a query if the building numbers are constant, that is, I'm assigning a group of people to the same buildings. Basically, (this is wrong) I want to do

insert into join (userid, buildingid) values ((select userid from users), 1)

Does that make sense? I've also tried using

select 1

The error I'm running into is that the subquery returns more than one result. I also attempted to create a join, basically with a static select query that was also unsuccessful.

Any thoughts?

Thanks, Chris

like image 907
Chris Thompson Avatar asked Aug 18 '09 05:08

Chris Thompson


People also ask

Can a subquery return a table of values?

A subquery selects and returns values to the first or outer SELECT statement. A subquery can return no value, a single value, or a set of values, as follows: If a subquery returns no value, the query does not return any rows.

Can we use subquery in insert?

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.


1 Answers

Almost! When you want to insert to values of a query, don't try to put them in the values clause. insert can take a select as an argument for the values!

insert into join (userid, buildingid)
select userid, 1 from users

Also, in the spirit of learning more, you can create a table that doesn't exist by using the following syntax:

select userid, 1 as buildingid
into join
from users

That only works if the table doesn't exist, though, but it's a quick and dirty way to create table copies!

like image 85
Eric Avatar answered Oct 21 '22 04:10

Eric