MySql查询2记录为1个结果

时间:2017-08-10 13:11:26

标签: php mysql subquery

我有一个表地址和一个表路线

路由存储2个地址ID和这些地点之间的距离 - > idStartidEnddistance

+-------+-------+-----+--------+
|idRoute|idStart|idEnd|distance|
+-------+-------+-----+--------+
|0      |1      |3    |2698    |
|1      |2      |4    |914     |
+-------+-------|-----+--------+


+---------+---------+-------------+
|idAddress|country  |city         |
+---------+---------+-------------+
|0        |USA      |Indianapolis |
|1        |Brasil   |Rio          |
|2        |Germany  |Munich       |
|3        |Argentina|Buenos Aires |
|4        |Italy    |Rome         |
+---------+---------+-------------+

`

所以我想查询并获取所有路线如下:

+-------+-------+-------+--------+---------+------+------------+--------+
|idRoute|idStart|idEnd  |CountryS|CountryE |CityS |CityE       |distance|
+-------+-------+-------+--------+---------+------+------------+--------+
|0      |1      |3      |Brasil  |Argentina|Rio   |Buenos Aires|2698    |
|1      |2      |4      |Germany |Italy    |Munich|Rome        |914    |
+-------+-------+-------+--------+---------+------+------------+--------+

如果我做一些子查询和外部查询一个特定的路由ID它将工作,因为我有一个特定的地方id =#

       SELECT
            ro.idRoute,
            ro.idStart,
            ro.idEnd,
            ro.distance,
            ro.time,
            (select a.country from address a 
            left join route ro 
                on (a.idAddress=ro.idStart)
            WHERE ro.idRoute='.$id .') as country_start,
            (select a.country from address a 
            left join route ro 
                on (a.idAddress=ro.idEnd)
            WHERE ro.idRoute='.$id .') as country_end, FROM route ro
        LEFT JOIN address a ON (a.idAddress=ro.idStart)
        LEFT JOIN countries c ON (a.country=c.code)
        WHERE ro.idRoute='.$id . $this -> presetFilter . ';

但在大多数情况下,我需要所有路线记录,而且我无法使其工作,因为对于子查询我会错过where声明。

外部查询 - > " set fieldname as outerResult"并在其中的内部查询语句????

中使用outerResult

1 个答案:

答案 0 :(得分:1)

您只需要从路由表中加入两次地址:一次用于IDstart,一次用于IdEnd。这是通过使用表别名来完成的,因此您可以引用地址表两次,当连接或引用字段时,数据库引擎知道对表的使用/需要的引用。

SELECT r.IdRoute
     , r.idstart
     , r.idend
     , Start_Add.country as CountryS
     , End_Add.country CountryE
     , Start_Add.city as CityS
     , End_Add.city as CityE
     , r.distancce
FROM route r
INNER JOIN Address Start_Add
 on r.IDStart= Start_Add.IdAddress
INNER JOIN address End_Add
 on r.IDEnd= End_Add.IdAddress