Mysql选择与另一个表字段相关的Statement

时间:2011-09-27 12:48:19

标签: mysql sql

我有两张桌子。一个是newBus,第二个是newPassengers。表newBus包含列startcity和endCity。现在让我们说newBus.startCity包含:

newBus.id----newBus.startCity-----newBus.endCity
    4             ACity        to     xCity
    5             tCity        to     MCity

newPassenger表: 3名乘客想去

newPassengers.s_city------newPassengers.e_city
    tCity             to       GCity
    OCity             to       FCity
    tCity             to       MCity

我想选择所有想要从tCity到MCity但是相对于newBus.id = 5的乘客。

2 个答案:

答案 0 :(得分:1)

SELECT newPassengers.id 
FROM newBus
    INNER JOIN newPassengers ON newPassengers.s_city = newBus.startCity
WHERE newPassengers.s_city = 'tCity' 
    AND newPassengers.e_city = 'MCity' 
    AND newBus.id = 5

这假设所有乘客都会乘坐与起始城市相同的起始城市的公交车,并且乘客的ID是newPassengers.id。您可以在选择列表中添加更多字段以获取您所需的信息。

答案 1 :(得分:0)

  

我想选择所有想要从tCity到MCity但是相对于newBus.id = 5的乘客。

SELECT p.id
FROM newpassengers p
INNER JOIN newbus b ON (p.s_city = b.startcity AND p.e_city = b.endCity)
WHERE p.s_city = 'tCity' AND p.e_city = 'MCity' AND b.id = '5';