简体   繁体   中英

issue with mysql query (group by)

SELECT DISTINCT(user),user,ip FROM logins GROUP by ip

This is supposed to select unique users from the logins table that have the same ip. For some reason it only returns one row. Users that do not have conflicting ips should not be pulled.

Is this what you want? :

SELECT DISTINCT
       logins1.user user1,
       logins2.user user2,
       logins1.ip
  FROM logins logins1
  JOIN logins logins2
    ON logins2.user > logins1.user
   AND logins2.ip = logins1.ip
;

The above will find each pair of distinct user s with an ip in common, together with that ip . (NB if more than two users all share an IP, this will return multiple rows for that IP. For example, with four users A/B/C/D, it will return six rows AB/AC/AD/BC/BD/CD. Is that OK?)

select user, ip from logins where ip in (
SELECT ip FROM logins group by ip HAVING COUNT(user) > 1)

DISTINCT means "different", if all your user has the same ip , then using GROUP BY ip will display only one record from your table. Your query is correct!

if you want to display all records but DISTINCT the user. (split off the repeated record, then just remove GROUP BY from the end of your query)

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