简体   繁体   中英

Distinct & Group SQL Query

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM