我有这样的架构
CREATE TABLE TrainManager(
train_name VARCHAR(5) REFERENCES Train(name),
station_id INT REFERENCES Station(station_id)
);
这两个参考表具有间接关系。
control(ctrl_id,train_name);
controlremote(ctrl_id,station_id);
尽可能地为了获得train name
和station id
,除了比较train_name和station_id之外,我们需要进入另外两个表来比较ctrl_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
但我想不出一个合适的SQL synatx来比较ctrl_id ......
答案 0 :(得分:3)
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
这样的事情。只需加入ctrl_id
上的两个表格即可。我希望我理解正确。