0

我有这样的架构

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 nameand ,除了比较 train_name 和 station_id 之外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 ...

4

1 回答 1

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

于 2012-05-21T02:31:07.637 回答