gpt4 book ai didi

php - MySql查询2条记录为1条结果

转载 作者:行者123 更新时间:2023-11-29 10:40:20 27 4
gpt4 key购买 nike

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

路线存储 2 个地址 ID 以及这些位置之间的距离 -> idStart , idEnd , distance .

+-------+-------+-----+--------+
|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,它会起作用,因为我得到了特定的 where 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 "并在内部查询的 where 语句中使用outerResult???

最佳答案

您只需从路由表中加入两次地址:一次用于 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

关于php - MySql查询2条记录为1条结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45614702/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com