dsx58940 2014-08-25 18:59
浏览 79
已采纳

PHP和MySQL搜索基于两个字段

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.

  • 写回答

1条回答 默认 最新

  • dongyan2267 2014-08-25 19:04
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题