我有一个像这样设置的表:
id | ip | name
---------------------------------
1 | 54.34.32.222 | John
2 | 23.44.64.843 | Rick
3 | 54.34.32.222 | John
4 | 23.44.64.843 | John
5 | 14.432.45.45 | Lisa
6 | 54.34.32.222 | Lisa
7 | 14.432.45.45 | Lisa
我只想为每个名字获取一个唯一的IP。例如," 54.34.32.222"约翰两次出现,所以我只想抓住第一排。但是" 54.34.32.222" Lisa也出现了,所以我也想抓住那个IP。
结果应如下所示:
id | ip | name
---------------------------------
1 | 54.34.32.222 | John
2 | 23.44.64.843 | Rick
4 | 23.44.64.843 | John
5 | 14.432.45.45 | Lisa
6 | 54.34.32.222 | Lisa
您如何计算名称出现的次数?这样做时,它会计算ip在名称中出现的次数,但我希望相反。
SELECT MIN(id), COUNT(name), ip, name FROM yourTable GROUP BY ip, name
答案 0 :(得分:3)
您从未提及如何确定在重复ip
- name
对的情况下要保留哪条记录。但是,根据您的示例输出,您似乎保留了具有最小id
值的记录。在这种情况下,我们可以在分组时采用MIN(id)
来获得所需的结果:
SELECT MIN(id), ip, name
FROM yourTable
GROUP BY ip, name
请按照以下链接查看正在运行的演示:
答案 1 :(得分:0)
您可以使用以下查询,该查询为任何给定名称选择IP地址的词汇最小值:
SELECT NAME, MIN(IP) AS IP
FROM TABLENAME
GROUP BY NAME
如果您需要与该名称的第一条记录相对应的IP地址(即记录中ID最低的记录):
SELECT NAME, IP
FROM TABLENAME TN
WHERE ID = (
SELECT MIN(ID)
FROM TABLENAME TN1
WHERE TN1.IP = TN.IP
AND TN1.NAME = TN.NAME
)
答案 2 :(得分:0)
这应该对你有用
SELECT min(id),ip,name FROM youTable group by ip,name
答案 3 :(得分:0)
您可能需要在此处对派生表进行连接以获得所需内容。您也可以进行子选择,但我会显示联接解决方案,因为大多数用例可能会更好。
SELECT
yourtable.id AS id,
ip,
name
FROM yourtable
/* join regular table to a derived table
* where you have selected the first row id for each user
*/
INNER JOIN (
SELECT MIN(id)
FROM yourtable
GROUP BY name
) AS min_id_per_name
ON yourtable.id = min_id_per_name.id
ORDER BY yourtable.id