1

I have two tables

Table 1

id name
1  New-York
2  Dallas
3  LA

Table 2

id name    city
1  Shops     1
2  Hotels    1
3  Shops     2
4  Hotels    2

How to get value of the city name table 1, in one query know row id of table 2?

Result:

1  Shops New-York
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
dev.nikolaz
  • 3,184
  • 3
  • 19
  • 32

2 Answers2

2

This is a simple inner join:

select
    t1.id,
    t2.name,
    t1.name
from
    towns t1
        join buildings t2
            on t1.id=t2.city

The query here will join the two tables and return the data as you wanted.

Having said that, you really should take a read of this Q&A that I put together for just these sorts of occasions. It is a lengthy read but will help you make sense of these sorts of simple joins (and a whole bunch more). How can an SQL query return data from multiple tables

-->How to join tables

Community
  • 1
  • 1
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
  • @echo_Me Not sure that a link to an answer showing how to join tables in an update statement is really adding a lot of value though is it when the user is simply asking how to run a simple query on two tables. I think the detailed link I added offered more value to someone learning to write queries. – Fluffeh Apr 05 '14 at 11:22
1
SELECT table2.id, table2.name, table1.name from table1, table2 where table1.id = table2.city
dikesh
  • 2,977
  • 2
  • 16
  • 26
  • It is good on SO to not only offer the code that solves the problem (if they are asking for code) but also explain what it is or how it works in at least some sort of detail. In this case, I know it is hard to explain it, but a code only answer rarely teaches the person much. – Fluffeh Apr 05 '14 at 11:16
  • Oh yes. Thanks @Fluffeh. I will keep this in mind next time !! Thanks for your advice ! :) – dikesh Apr 05 '14 at 11:19