Reputation: 3433
I have a schema like this
CREATE TABLE TrainManager(
train_name VARCHAR(5) REFERENCES Train(name),
station_id INT REFERENCES Station(station_id)
);
The two reference tables have an indirect relations.
control (ctrl_id, train_name);
controlremote (ctrl_id, station_id);
As you can, in order to get train name
and station id
, we need to get into the other two tables to compare ctrl_id
besides comparing the train_name and station_id.
$query = "INSERT INTO `train` (train_name, station_id)
SELECT t.train_name, st.station_id
FROM train, station
WHERE t.train_name = ( SELECT c.train_name FROM control c
WHERE c.train_name = t.train_name)
AND
st.station_id = ( SELECT cr.station_id FROM controlremote cr
WHERE cr.station_id = st.station_id)
AND
But I can't think of a proper SQL synatx to compare the ctrl_id ...
Upvotes: 0
Views: 91
Reputation: 2943
INSERT INTO `train` (train_name, station_id)
SELECT control.train_name, controlremote.station_id
FROM control
LEFT JOIN controlremote ON control.ctrl_id = controlremote.ctrl_id
Something along this way. Just join both tables on ctrl_id
. I hope I understood correctly.
Upvotes: 3