如何检索列的相应值?

时间:2013-05-24 06:27:25

标签: mysql

我有两个表,一个名为logs,另一个名为location

logs中,我有以下内容:

___________________________
| id | message | location |
'-------------------------'
| 1  | test    | 1        |
| 2  | test    | 2        |
| 3  | test    | 1        |
| 4  | test    | 1        |
___________________________

location表中,我有这个:

_________________
| id | location |
'---------------'
| 1  | US       |
| 2  | UK       |
_________________

我想用我的查询输出的是:

___________________________
| id | message | location |
'-------------------------'
| 1  | test    | US       |
| 2  | test    | UK       |
| 3  | test    | US       |
| 4  | test    | US       |
___________________________

我该怎么做?

5 个答案:

答案 0 :(得分:1)

试试这个:

select lg.id, lg.message, lo.location 
from logs lg, location lo 
where lg.location = lo.id

答案 1 :(得分:1)

SELECT logs.id, logs.message,location.location 
from logs, location 
where logs.location= location.location 

在此查询中应用的加入是内连接。

答案 2 :(得分:0)

 select a.id,a.message,b.location 
 from 
 logs a , location b 
 where 
 logs.location = location.id;

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

答案 3 :(得分:0)

使用以下查询。

SELECT a.id, a.message, b.location 
      FROM logs a 
           LEFT JOIN location b 
           ON a.location = b.id;

答案 4 :(得分:0)

试试这个

 SELECT lo.id,message,location
 FROM logs lo ,location l
 WHERE lo.location = l.id