【问题标题】:SQL Query to compare two columns with one column from another table (and get two values)SQL Query 将两列与另一表中的一列进行比较(并获取两个值)
【发布时间】:2017-09-05 11:18:15
【问题描述】:

是否有可能根据table1 中两列的ID 值,在table2 中得到它们的等价物?

我的table1 看起来像这样:

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

table2,像这样:

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

我想得到这样的东西:

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

我尝试做两个查询:

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

和:

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

但是如果我从一个表中删除一个值,另一个表会继续索引该行,因此存在未定义的偏移问题。

【问题讨论】:

    标签: php mysql sql-server join


    【解决方案1】:

    你可以加入第二张桌子两次:

    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
    

    注意:"destiny""destination" 不是一回事。

    【讨论】:

    • 感谢您的快速回答:)
    【解决方案2】:

    你可以在一个简单的查询中做到这一点:

    SELECT t1.id,t1.origin,t1.destiny,o.name as nameOrigin, d.name as nameDestiny  
    FROM t1,t2 o, t2 d 
    WHERE t1.origin=o.id AND t1.destiny=d.id
    

    我在这里附上 SQL 小提琴链接。 http://sqlfiddle.com/#!9/ecf5ae

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多