从两个表中查询一个语句?

时间:2011-04-01 09:14:00

标签: mysql sql

我有2张桌子

User
-userid
-group
//other unrelated columns

Logs
-userid
-ip

我想要做的是使用IP查询所有用户ID的Logs表,然后获取所有userid的组。单个查询可以实现吗?如果没有,那么除了用userid查询每个用户行之外还有加速吗?

5 个答案:

答案 0 :(得分:3)

这样的东西?

SELECT ip, userid, group
FROM Logs INNER JOIN User ON Logs.userid = User.userid
WHERE ip = '1.2.3.4'

答案 1 :(得分:3)

当然这是一个简单的连接?

select logs.userid,logs.ip,user.group
from logs
left join user on logs.userid=user.userid

答案 2 :(得分:2)

select distinct group 
from user u
join logs l on u.userid=l.userid
where l.ip='yourIP'

答案 3 :(得分:1)

您应该可以通过加入(http://dev.mysql.com/doc/refman/5.0/en/join.html

来实现
select User.group
from Logs
   inner join User on Logs.userid = User.userid
where Logs.ip = 'IP';

答案 4 :(得分:1)

至少回溯一些作为关键字(组)或可能是特殊(用户)的字段名称

SELECT L.`group`
FROM Logs L
INNER JOIN `User` U ON U.userid = L.userid
WHERE L.ip = '1.2.3.4'
GROUP BY L.`group`