douzizang7783 2017-04-10 12:06
浏览 147
已采纳

SQL Query将两列与另一个表中的一列进行比较(并获取两个值)

Is it possible to, based on the ID value of two columns from table1, get their equivalent in table2?

My table1 looks like this:

id | origin | destiny
-- | ------ | -------
1  | 2      | 3
2  | 4      | 5

and table2, like this:

id | name
-- | ----
1  | bla
2  | asd
3  | dfg
4  | qwe
5  | tle

And I want to get something like this:

id | origin | destiny | nameOrigin | nameDestiny
-- | ------ | ------- | ---------- | -----------
1  | 2      | 3       | asd        | dfg
2  | 4      | 5       | qwe        | tle

I tried to do two queries:

SELECT
    t1.origin, 
    t1.destiny,
    t2.name
FROM 
    table1 t1 
INNER JOIN table2 t2 ON t1.origin = t2.id

and:

SELECT
    t1.origin, 
    t1.destiny,
    t2.name as destinyName
FROM 
    table1 t1 
INNER JOIN table2 t2 ON t1.destiny = t2.id

But if I delete a value from one table, the another one keeps indexing that row hence there is an undefined offset problem.

  • 写回答

2条回答 默认 最新

  • dongshanyan0322 2017-04-10 12:11
    关注

    You can join the second table twice:

    SELECT      t1.id,
                t1.origin, 
                t1.destiny,
                o.name as nameOrigin,
                d.name as nameDestiny
    FROM        table1 t1 
    INNER JOIN  table2 o ON t1.origin = o.id
    INNER JOIN  table2 d ON t1.destiny = d.id
    

    NB: "destiny" is not the same thing as "destination".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能