我有这样的架构

CREATE TABLE TrainManager(
    train_name    VARCHAR(5) REFERENCES Train(name),
    station_id      INT REFERENCES Station(station_id)
);


这两个参考表具有间接关系。


  控制(ctrl_id,train_name);
  
  controlremote(ctrl_id,station_id);


尽可能地,为了获取train namestation 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语法来比较ctrl_id ...

最佳答案

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。我希望我能正确理解。

09-26 08:18