-6

I have a problem ... In table1 I have an id, I have to compare that id in table2, then fetch the second id that is in table2 and compare it to table3 and get as a result a datum. Example

TABLE1
ID   NAME ECC...
1      Jhon
2      Frank

TABLE2
ID ID2 ECC..
1   4
2   8

TABLE3
ID NAME
4    Sea
8    Hello

If I look for id 1, the result must be Sea If I look for id 2 the result must be Hello

Thanks!

S3S
  • 24,809
  • 5
  • 26
  • 45
falco3205
  • 1
  • 1
  • 2

5 Answers5

1
 SELECT Table3.NAME
   FROM Table1
  INNER JOIN Table2
 ON Table1.ID = Table2.ID
  INNER JOIN Table3
 ON Table3.ID = Table2.ID2
  WHERE Table1.ID = 1  -- Your Search here
Esteban P.
  • 2,789
  • 2
  • 27
  • 43
0

You should use joins.

Your query will look like :

SELECT t3.name
FROM table3 t3
LEFT JOIN table2 t2 ON t3.id = t2.id2
LEFT JOIN table1 t1 ON t2.id2 = t1.id
WHERE t1.id = <your_number>
Iksen
  • 24
  • 2
-1

Query:

 SELECT a.name As Name FROM table3 a JOIN 
 (SELECT b.id2 AS id FROM table1 a JOIN table2 b ON a.id = b.id)b
 ON a.id = b.id where b.id = <your id number (1,2) Anything>
Gauravk
  • 49
  • 4
-1
select Table2.Id,Table3.Name from Table1 inner join Table2 on Table2.ID2 = Table3.Id
Nithin
  • 1,376
  • 12
  • 29
-2

Should be something like this:

select table3.name as name3
from table3
where table3.ID = table2.ID2
and table2.ID = table1.ID
and table1.ID = <YOURNUMBERHERE>
Paladin
  • 1,637
  • 13
  • 28
  • 3
    you're missing a few joins here.... – S3S Jun 13 '17 at 13:13
  • @scsimon doing some implicit joins with where-and combinations, one can also perform this with LEFT JOIN and so on, but it wrote it out of my head, so no joins ;) But you are right, JOIN would be the best way – Paladin Jun 13 '17 at 13:15
  • No, there are no implicit joins here, `table2` and `table1` are not mentioned in the `from` clause – HoneyBadger Jun 13 '17 at 13:16