tags:

views:

30

answers:

2

I have two tables. Say:

This is table 1
+--------+-----------------------+
| stuff  | foreing   | foreing2  |
+--------+-----------------------+
| bazzzz |       555 |       666 |
+--------+-----------------------+

This is table 2
+-----------------------+
| id_table | values     |
+-----------------------+
|      555 | Foo        |
+-----------------------+
|      666 | Bar        |
+-----------------------+

What I want is a SQL query that gives me a row with this info:

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

This is what I tried to do, but actually it returns two rows, which is not what I want:

SELECT table1.stuff,
    table2.values as value1,
    table2.values as value2
    WHERE table1.foreing = table2.id_table
    OR table1.foreing2 = table2.id_table
A: 

You shall have to make inner queries like this:

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
Kangkan
Not necessarily - see The King's answer.
Mark Bannister
@Mark: Thats right. that is another way to go.
Kangkan
+3  A: 

Since you need to match two columns with the same child table... you need to refer the child table twice...

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
The King
Counting down to comment about explicit join syntax in 3... 2... 1...
Mark Bannister