简体   繁体   English

在一个表中查找每个ID,在另一表中插入行

[英]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. 表“位置”是一对多/一对与具有外键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. 现在,我想为“ locations”中的每个现有“ locations.id”添加一个“ resources”中的记录,其中包含名称和值的默认值以及location_id。

I tried query below which generates partially the desired result, because this sql query dosent set values for 'resoruces.name' and 'resources.value'. 我尝试在下面的查询中部分生成所需的结果,因为此sql查询指定了“ resoruces.name”和“ resources.value”的值。 They should be respectively "standard" and "1". 它们应分别为“标准”和“ 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: 如果表resources尚不存在,这应该可以工作:

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. 字符串文字会根据您所使用的RDBMS而有所不同。 For instance, I believe MySQL uses backticks and not single quotes. 例如,我相信MySQL使用反引号而不是单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM