如何从表中查询两个不同的字段,并使它出现在同一行?

时间:2010-08-02 04:57:21

标签: sql sqlite

我有两张桌子。说:

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 个答案:

答案 0 :(得分:3)

由于您需要使用相同的子表匹配两个列...您需要两次引用子表...

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

答案 1 :(得分:0)

你必须做出这样的内部查询:

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