Distinct & Group SQL Query

微笑、不失礼 提交于 2019-12-11 16:33:50

问题


I have a little bit complex MySQL query for me and i can't figure out how to write it without eating tons of memory. ( i don't really mind if it would )

I have the following table:

              TABLE: users(id,ip)
              ------------------------------------
              4BF1510 | 40.145.10.99 <-- SAME IP (A)
SAME ID   --> 510SD55 | 65.12.105.42 
SAME ID   --> 510SD55 | 45.184.15.10
              201505V | 40.145.10.99 <-- SAME IP (A)
              984AZ6C | 72.98.45.76
                      | 10.15.78.10  <-- SAME IP (B)
                      | 10.15.78.10  <-- SAME IP (B)
SAME ID   --> B1D56SX |  
SAME ID   --> B1D56SX |  

I want a query that only fetchs 1 item per a unique id or ip, So:

4BF1510 | 40.145.10.99
510SD55 | 65.12.105.42
984AZ6C | 72.98.45.76
        | 10.15.78.10
B1D56SX |

The Most important things:

  • If multiple entries have the same IP and same ID -> they'll be grouped
  • If multiple entries have the same IP but different IDs -> they'll not be grouped
  • If multiple entries have the same ID but different IPs -> they'll be grouped
  • If multiple entries have the same IP but empty ID fields -> they'll be grouped
  • If multiple entries have the same ID but empty IP fields -> they'll be grouped

Which means that the ID should have the first priority of trust, Because multiple users may use the same IP.

Any effective way to achieve that?

Tons of thanks.


回答1:


What you are wanting to do can be accomplished using group_contact.

Example

SELECT id, GROUP_CONCAT(ip) as ips FROM logs group by id

edit: forgot group by



来源:https://stackoverflow.com/questions/4379559/distinct-group-sql-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!