SQLite3,将多行合并为一行
我有两张表:城市(如C)和路线(如R) C: R: (我的期望):我希望将我的表合并并连接到以下表单:SQLite3,将多行合并为一行,sql,sqlite,join,Sql,Sqlite,Join,我有两张表:城市(如C)和路线(如R) C: R: (我的期望):我希望将我的表合并并连接到以下表单: ____ ______ ____________ ____ __________ __________ | id | from | fromAsText | to | toAsText | distance | |____|______|____________|____|__________|__________| | 1 | 1 | A | 2 | B
____ ______ ____________ ____ __________ __________
| id | from | fromAsText | to | toAsText | distance |
|____|______|____________|____|__________|__________|
| 1 | 1 | A | 2 | B | 100 |
| 2 | 2 | B | 1 | A | 100 |
|____|______|____________|____|__________|__________|
添加一个值不是问题
SELECT
r.*
s.city as fromAsText
FROM
routes as r,
cities as s
WHERE
r.from = s.id
但是我不知道如何实现我的目标!谢谢 只需加入城市表两次:
select r.id, r.from, c_from.city as from_city, r.to, c_to.city as to_city, r.distance
from routes r
join cities c_from on c_from.id = r.from
join cities c_to on c_to.id = r.to
order by r.id;
您确定预期结果正确吗?请不要使用逗号分隔的联接。在标准SQL 1992中有冗余!改为使用显式连接:
从路由作为r内部连接城市作为c ON c.id=r.FROM
。Argh,出现错误,预期已更新
SELECT
r.*
s.city as fromAsText
FROM
routes as r,
cities as s
WHERE
r.from = s.id
select r.id, r.from, c_from.city as from_city, r.to, c_to.city as to_city, r.distance
from routes r
join cities c_from on c_from.id = r.from
join cities c_to on c_to.id = r.to
order by r.id;