MySQL无法很好地表达这种情况

时间:2012-01-12 23:33:25

标签: mysql

假设我有一个ip地址和用户ID表。

user_id | ip_address
---------------------
1       | 127.0.0.1
13      | 127.0.0.1
27      | 192.168.0.1
47      | 127.0.0.1
59      | 192.168.0.1
70      | 127.0.0.1

给出的是用户ID,我们会说1.我想要做的是选择共享用户ID为1的IP地址的所有用户ID。

我假设有某种词比“我不知道”更能澄清这种情况,但我不确定。

我还要补充一点,我试图避免使用子查询。

2 个答案:

答案 0 :(得分:4)

SELECT user_id FROM tablename 
WHERE ip_address in (
  SELECT ip_address FROM tablename where user_id=1
);

或没有子查询:

SELECT righttable.user_id AS user_id
FROM
  tablename AS lefttable
  INNER JOIN tablename AS righttable ON lefttable.ip_address=righttable.ip_address
WHERE lefttable.user_id=1
;

答案 1 :(得分:1)

我认为你想要(假设每个用户有1条记录):

select user_id, ip_address
from user_ips
where 
  ip_address = (
    select ip_address from user_ips where user_id=1
  );

更新这不比子查询好,但你也可以这样做:

select matches.user_id
from user_ips needle, user_ips matches
where needle.user_id = 1
and needle.ip_address = matches.ip_address