简体   繁体   English

将sql表内容从一个表复制到另一个表 - 有条件地

[英]Copying sql table contents from one table to another - conditionally

I have 2 tables positions - which contains one field called ' tripname ' trips - which contains a field called ' name ' 我有2代表positions -它包含一个字段名为“ tripnametrips -它包含了一个名为“字段name

I use a csv file from which data is imported in to these two tables and now I need to do some further updating and am a little stuck. 我使用一个csv文件从中导入数据到这两个表,现在我需要做一些进一步的更新,我有点卡住了。

The ' positions ' table is updated by the addition of as many rows as are contained in the csv files. 通过添加csv文件中包含的行数来更新“ positions ”表。 One field is called ' tripname ' (which contains a value) another is called ' FK_Trips_ID ' (which is added as NULL). 一个场被称为“ tripname ”(其中包含一个值)的另一个被称为“ FK_Trips_ID ”(其被添加作为NULL)。

The ' trips ' table is updated with only one row (if it did not already exist)which contains a field called 'name' and another called 'ID'. ' trips '表只更新了一行(如果它还不存在),其中包含一个名为'name'的字段和另一个名为'ID'的字段。

Here's where I am stuck. 这是我被困的地方。 I need to: 我需要:

Insert into the 'positions.FK_Trips_ID' field the value of the 'trips.ID'
where the 'trips.name' is equal to the 'positions.tripname
- BUT only if 'positions.FK_Trips_ID' is NULL

I cannot find a similar example of this type of insertion and wondered if some kind soul could point me in the right direction. 我找不到这种类型插入的类似例子,并想知道某种灵魂是否能指出我正确的方向。

I think what you mean is to UPDATE column FK_Trips_ID from table positions based on the matching record on the trips table. 我想你的意思是UPDATEFK_Trips_ID从表positions基于对匹配的记录trips表。

You can join both table to have only one request on the database, 您可以将两个表连接到数据库上只有一个请求,

UPDATE  positions a
        INNER JOIN trips b
            ON a.tripname = b.name
SET     a.FK_Trips_ID = b.ID
WHERE   a.FK_Trips_ID IS NULL

For faster performance of the UPDATE statement, the columns must be index to avoid from performing Full Table Scan which causes slow when doing it on large databases. 为了更快地执行UPDATE语句,列必须是索引以避免执行全表扫描 ,这会导致在大型数据库上执行此操作时速度变慢。

ALTER TABLE positions ADD INDEX (tripname);
ALTER TABLE trips ADD INDEX (name);

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

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