Php 在mysql中查找2个变量(mybe唯一值)我找不到更好的标题
有人知道怎么才能找到吗? 我有三个专栏 1-id 2-用户名 3-ip 样本数据为:Php 在mysql中查找2个变量(mybe唯一值)我找不到更好的标题,php,mysql,find,Php,Mysql,Find,有人知道怎么才能找到吗? 我有三个专栏 1-id 2-用户名 3-ip 样本数据为: +----+-----------+----------------+ | id | username | ip | +----+-----------+----------------+ | 1 | John | 127.0.0.1 | | 2 | John | 127.0.0.1 | | 3 | John | 127.0
+----+-----------+----------------+
| id | username | ip |
+----+-----------+----------------+
| 1 | John | 127.0.0.1 |
| 2 | John | 127.0.0.1 |
| 3 | John | 127.0.0.1 |
| 4 | John | 127.0.0.1 |
| 5 | John | 127.0.0.1 |
| 6 | John | 127.0.0.2 |
| 7 | John | 127.0.0.2 |
| 8 | John | 127.0.0.3 |
| 9 | John | 127.0.0.1 |
| 10 | John | 127.0.0.1 |
| 11 | John | 127.0.0.1 |
| 12 | Pit | 127.1.1.1 |
| 13 | Pit | 127.1.1.1 |
| 14 | Pit | 127.1.1.1 |
| 15 | Pit | 127.1.1.1 |
| 16 | Pit | 127.1.1.1 |
| 17 | Pit | 127.1.1.1 |
+----+-----------+----------------+
所以我想找到任何有重复ip的值
在更好的情况下,我希望找到唯一值,以便通过此查询可以找到它:
SELECT distinct `username`, `ip` FROM `logs`
现在查询结果是
+----+-----------+----------------+
| id | username | ip |
+----+-----------+----------------+
| 1 | John | 127.0.0.1 |
| 7 | John | 127.0.0.2 |
| 8 | John | 127.0.0.3 |
| 12 | Pit | 127.1.1.1 |
+----+-----------+----------------+
很好,但我真正想要的是什么?
我想找到任何用户名都有重复的ip,因此结果必须:
+----+-----------+----------------+
| id | username | ip |
+----+-----------+----------------+
| 1 | John | 127.0.0.1 |
| 7 | John | 127.0.0.2 |
| 8 | John | 127.0.0.3 |
+----+-----------+----------------+
因为那里没有重复的ip
如何从结果中删除坑?请尝试以下操作-
SELECT `logs`.`username`, `logs`.`ip`
FROM (
SELECT `username`
FROM `logs`
GROUP BY `username`
HAVING COUNT(DISTINCT `ip`) > 1
) AS `dups`
INNER JOIN `logs`
ON `dups`.`username` = `logs`.`username`
GROUP BY `logs`.`username`, `logs`.`ip`;
更新随着数据集的增长,在用户名和ip上添加索引会大大提高查询的性能-
CREATE INDEX `IX_username_ip` ON `logs` (`username`, `ip`);
试试这个
SELECT l1.username, l1.ip FROM logs l1
INNER JOIN logs l2
ON l2.username = l1.username
AND l2.ip != l1.ip
GROUP BY l1.username, l1.ip
@用户131;你是否因为没有帮助或者你甚至没有尝试过而对此投了反对票?这不会产生他想要的结果,你错过了
按用户名分组
@nnichols按用户名分组在这里是不需要的,而GROUP_concat也可以在没有分组的情况下工作,是你投了我的答案的反对票吗?我没有投反对票回答。如果没有分组依据
,您的查询将不会给出所需的结果!非常感谢,这很好,工作很好,但我不知道这个查询是如何工作的?您能给我一个如何进行此查询的参考吗?内部查询(派生表dups)只创建一个用户名列表,其中有多个ip。然后将其连接回日志表以检索ip地址。如果您满意,请接受此答案。只需点击你想要接受的答案左边的勾号。
select distinct username,group_concat( distinct ip ) ,count(distinct ip) as cnt from table_name group by username having cnt>1;
SELECT l1.username, l1.ip FROM logs l1
INNER JOIN logs l2
ON l2.username = l1.username
AND l2.ip != l1.ip
GROUP BY l1.username, l1.ip