3

我有这两个表:

表一:用户

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

表二:面积

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

我想要这样的结果:

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

由于我不擅长 sql 查询,所以如何编写选择查询。有什么想法或建议吗?谢谢。

4

3 回答 3

5

试试喜欢

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

并尽量避免mysql_*声明,因为整个ext/mysql PHP扩展提供了所有以前缀命名的函数mysql_*,从 开始正式弃用,并将在未来PHP v5.5.0被删除。

您可以更好地使用其他两个MySQL扩展:MySQLiPDO_MySQL,其中任何一个都可以用来代替ext/mysql.

于 2013-09-04T11:20:36.330 回答
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
于 2013-09-04T11:24:33.980 回答
0

SQL是这样的:

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

但是,请阅读我为这种情况而写的这个问答

于 2013-09-04T11:21:22.013 回答