3

I have this two table:

Table One: user

id   name   home_location    job_location
1    Jack   40               5
2    Rocky  50               4  
3    Tom    24               9

Table Two: area

area_id    area_name
5          Bukit Batok
4          Bukit Panjang
9          Boon Lay
40         Pioneer
50         Choa Chu Kang
24         Clementi

I want result like this:

ID    name    home_location   job_location
1     Jack    Pioneer         Bukit Batok
2     Rocky   Choa Chu Kang   Bukit Panjang
3     Tom     Clementi        Boon Lay

As i am not good in sql query so how to write select query. Any ideas or suggestions? Thanks.

Manan
  • 1,197
  • 4
  • 15
  • 25

3 Answers3

5

Try like

SELECT id as ID,
             name,
             area_1.area_name as home_location,
             area_2.area_name as job_location,
             area_1.area_id as home_location_id,
             area_2.area_id as job_location_id   
FROM user 
INNER JOIN 
      area AS area_1 
           ON area_1.area_id = user.home_location
INNER JOIN 
      area AS area_2
           ON area_2.area_id = user.job_location

And try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.

There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.

GautamD31
  • 28,552
  • 10
  • 64
  • 85
1
Select U.ID,U.Name,A1.Area_Name as Home_Location, A2.Area_name as Job_Location
From Users U
Left Outer Join Area A1 ON U.home_location = A1.Area_ID
Left Outer Join Area A2 ON U.job_location = A2.Area_ID
Awais Amir
  • 165
  • 10
0

The SQL is this:

select
    us.name,
    us.home_location,
    ar.job_location
from
    user us
        join area ar
            on us.area_id=ar.id

but please, take a read of this Q&A I wrote for justthis situation.

Community
  • 1
  • 1
Fluffeh
  • 33,228
  • 16
  • 67
  • 80