简体   繁体   中英

Foreach id in one table, insert row in another table

I have two tables. Table 'locations' is One-To-Many/One related with table 'resources' with foreign key location_id. Something like this

locations -> id | location
resources -> id | location_id | name | value

I have a lot of records in 'locations'. Now i want to add for each existing 'locations.id' in 'locations', a record in 'resources' with default values for name and value and the location_id of course.

I tried query below which generates partially the desired result, because this sql query dosent set values for 'resoruces.name' and 'resources.value'. They should be respectively "standard" and "1".

INSERT INTO service_categories(location_id) SELECT id FROM locations;

I just cant construct the query with adding values for this fields. How to do this? The result which i want is something like this:

    id | location_id | name     | value
-------------------------------------
    1  | 1           | Standard | 1
    2  | 2           | Standard | 1
    3  | 3           | Standard | 1
    4  | 4           | Standard | 1
    5  | 5           | Standard | 1
    6  | 6           | Standard | 1
    7  | 7           | Standard | 1
    8  | 8           | Standard | 1
....

This should work, if the table resources doesn't already exist:

SELECT
    location_id as id,
    location_id,
    'Standard' as name,
    1 as value
INTO resources
FROM locations

If the table does already exist then you'd write this instead:

INSERT INTO resources (id, location_id, name, value)
SELECT
    location_id as id,
    location_id,
    'Standard' as name,
    1 as value
FROM locations

The string literal will vary based on which RDBMS you're using. For instance, I believe MySQL uses backticks and not single quotes.

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