对此最好的查询是什么?

时间:2013-08-01 06:39:19

标签: mysql sql database select exists

我有表bus,street,route_going,route_return

在桌子街上,我有

示例:

id | name
1  | street1 
2  | street2
3  | street4
...
n  | streetn

表route_going,我有例子:

id_bus | id_street | order
101    | 1         | 1
101    | 2         | 2
101    | 5         | 3

...

表route_return,我有例子:

id_bus | id_street | order
101    | 3         | 1
101    | 2         | 2
101    | 1         | 3

...

好的,在这个例子中,公共汽车101按此顺序从街道1,2和5行进。然后公共汽车从街道3,2和1顺序返回。

我想知道哪条公共汽车经过街道'x'和街道'y'(前x,后y)

例如:

x = 1, y = 5 -> the bus 101 pass
x = 1, y = 3 -> the bus 101 pass
x = 3, y = 1 -> the bus 101 pass
x = 3, y = 5 -> the bus 101 don't pass

所以,我发现公共汽车的sql是......(例如,路过1号和5号街道)

select * from bus as b where 
-- The bus passes between the 2 streets at the going route??
exists (select * from route_going as rg1, route_going as rg2,street as r1,street as r2 where rg1.id_bus = rg2.id_bus and rg1.id_street = r1.id and rg2.id_street = r2.id and r1.id = 1 and r2.id = 5 and b.bus_id = rg1.id_bus and rg1.order <= rg2.order)
-- The bus passes between the 2 streets at the return route??
or exists (select * from route_return as rg1, route_return as rg2,street as r1,street as r2 where rg1.id_bus = rg2.id_bus and rg1.id_street = r1.id and rg2.id_street = r2.id and r1.id = 1 and r2.id = 5 and b.bus_id = rg1.id_bus and rg1.order <= rg2.order)
-- The bus passes between the 2 streets at the going route first and return route later??
or exists (select * from route_going as rg1, route_return as rg2,street as r1,street as r2 where rg1.id_bus = rg2.id_bus and rg1.id_street = r1.id and rg2.id_street = r2.id and r1.id = 1 and r2.id = 5 and b.bus_id = rg1.id_bus)

所以,我认为这个查询并不好。有人可以帮我说一下这次搜索的“最佳”查询吗?

2 个答案:

答案 0 :(得分:2)

SET @x = 1;
SET @y = 5;

SELECT x.id_bus
  FROM   
     ( SELECT *,0 returning FROM route_going UNION SELECT *, 1 FROM route_return ) x
  JOIN
     ( SELECT *,0 returning FROM route_going UNION SELECT *, 1 FROM route_return ) y
    ON y.id_bus = x.id_bus
   AND (y.returning > x.returning OR (y.returning = x.returning AND y.porder > x.porder))
 WHERE x.id_street = @x
   AND y.id_street = @y;

答案 1 :(得分:0)

select 
street.name,
route_going.id_bus,route_going.id_street
route_return.id_bus,route_return.id_street
on street.id=route_going.id_street and 
route_return.id_street=route_going.id_street;  

试试这个。感谢