MYSQL从列插入特定数据

时间:2016-02-07 15:35:58

标签: mysql

我有一个名为Pupils的表和一个名为Bus的表。

总线包含一个ID,Destination(它去往的地方)和Time(当它离开时)。

学生包含姓名,位置(居住地)和BusID(需要乘坐的公交车)。

我想填写' BusID'列中包含正确的ID'来自' Bus'表(取决于瞳孔的位置和时间选择)。

例如,学生住在特拉维夫,并希望在10点开一辆公共汽车。

我需要填写他的' BusID'列 AND ROW (有很多学生)具有相同的ID'在总线表中,目的地等于特拉维夫,时间等于10:00。

它是否可能?我正在考虑使用Insert into / Insert into select,但它并不能满足我的需求。

1 个答案:

答案 0 :(得分:0)

正如我同时所理解的那样:学生们在其他地方(大概不在T.A.)并想找到将他们带回T.A.的公共汽车。在10:00。

然后可以通过

实现
-- The id of the bus that travels at 10:00 to T.A.:
select id from bus where destination='Tel Aviv' and time='10:00:00';

-- Update the pupil's record with the bus-id:
update pupils set busid=... where location='Tel Aviv';

-- Together (and that's the answer):
update pupils set busid=(select id 
                           from bus 
                          where destination='Tel Aviv' 
                            and time='10:00:00')
              where location='Tel Aviv';

请注意,这假设在第一个查询中只有一个结果行,即恰好是一个10点钟到T.A的总线。