2012-05-21 78 views
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 namestation id,我們需要進入其他兩個表進行比較ctrl_id除了比較train_name和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 

但我想不出一個適當的SQL synatx比較ctrl_id的......沿着這條道路

回答

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這兩個表。我希望我理解正確。

+0

非常感謝您的幫助。現在很清楚。我在我的項目中始終使用相同的想法。謝謝。 – user1012451