简体   繁体   中英

PHP And MySQL Search Based on two fields

Alright, so I understand how to do a mysql query to return results based on one search parameter. But I have a table that contains usernames and data. The data should be unique to each username, but I want to return any instances where that data might overlap over multiple usernames. An example would be

    Username | Data Field
    ----------------------------------------------
    Test     | Abcd1234
    Test2    | efgh5678
    Test3    | Abcd1234
    Test4    | efgh5678

I want my php script to return all instances where duplicate entries are found in the data field. Note that, neither the data field nor username field are unique in this table. The table gets populated whenever the user completes an action, so there should be many entries for each username, but each time they should have the same data field. I only want to check when two different usernames have the same data field. Does anyone have any idea how this can be done in php or a mysql select statement? It may take more than one query and that is okay. I've tried searching on how to find duplicate emails based on usernames, but the results I found were more on preventing duplicate registrations in the first place.

Basically, you want to count the number of unique users for each data field. This is an aggregation query:

select data, count(distinct username) as numusers
from table t
group by data;

You should be able to get the unique user names with this query:

select data, count(distinct username) as numusers,
       group_concat(distinct username) as users
from table t
group by data
having count(distinct username) > 1;

This will create a comma separated list of users "using" the same data.

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