【问题标题】:SQLite3, Combine multiple rows in oneSQLite3,将多行合二为一
【发布时间】:2019-11-25 11:04:34
【问题描述】:

我有两张表城市(如 C)和路线(如 R)

C:

 ____ ______
| id | city |
|____|______|
| 1  |  A   |
| 2  |  B   |
|____|______|

R:

 ____ ______ ____ __________
| id | from | to | distance |
|____|______|____|__________|
| 1  |  1   | 2  | 100      |
| 2  |  2   | 1  | 100      |
|____|______|____|__________|

(我的期望):我想将我的表格合并并加入以下表格:

 ____ ______ ____________ ____ __________ __________
| 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

但我没有任何想法如何实现我的目标!谢谢!

【问题讨论】:

  • 你确定你的预期结果正确吗?
  • 请不要使用逗号分隔的连接。在标准 SQL 1992 中有冗余!改用显式连接:FROM routes as r INNER JOIN cities as c ON c.id = r.from.
  • Argh,出现错误,预期已更新

标签: sql sqlite join


【解决方案1】:

只需加入城市表两次:

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;

【讨论】:

    猜你喜欢
    • 2015-11-08
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    相关资源
    最近更新 更多