简体   繁体   中英

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 '

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.

The ' positions ' table is updated by the addition of as many rows as are contained in the csv files. One field is called ' tripname ' (which contains a value) another is called ' FK_Trips_ID ' (which is added as 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'.

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.

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.

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

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