代码之家  ›  专栏  ›  技术社区  ›  Cristian

如何从一个表中查询两个不同的字段,并使其显示在同一行中?

  •  0
  • Cristian  · 技术社区  · 14 年前

    我有两张桌子。说:

    This is table 1
    +--------+-----------------------+
    | stuff  | foreing   | foreing2  |
    +--------+-----------------------+
    | bazzzz |       555 |       666 |
    +--------+-----------------------+
    
    This is table 2
    +-----------------------+
    | id_table | values     |
    +-----------------------+
    |      555 | Foo        |
    +-----------------------+
    |      666 | Bar        |
    +-----------------------+
    

    我想要的是一个SQL查询,它给我一个包含以下信息的行:

    +--------+-----------------------+
    | stuff  | value1    | value2    |
    +--------+-----------------------+
    | bazzzz | Foo       | Bar       |
    +--------+-----------------------+
    

    这是我试图做的,但实际上它返回两行,这不是我想要的:

    SELECT table1.stuff,
        table2.values as value1,
        table2.values as value2
        WHERE table1.foreing = table2.id_table
        OR table1.foreing2 = table2.id_table
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   The King    14 年前

    Select table1.Stuff, B.Vales as Value1, C.Values as Value2
     From table1, table2 as B, table2 as C
       Where table1.foreing = B.id_table and table1.foreing2 = C.id_table
    
        2
  •  0
  •   Kangkan    14 年前

    你必须进行如下内部查询:

    SELECT table1.stuff,
        (select table2.values as value1 where table2.id_table=table1.foreing),
        (select table2.values as value2 where table2.id_table=table1.foreing2)
        from table1