doupuxuan5784 2013-03-03 14:03
浏览 497
已采纳

MySQL“FIELD_IN_SET()”等效于“已加入”表

I'm searching for an equivalent for MySQL "FIELD_IN_SET()" with joined tables. Here is an example of what I want to do.

I have three tables. The first contains fields "user_id" and "user_name". The second contains fields "id", "user_id" and "role_id". The third contains "id", "role_name".

I want to search for users that owns two different specified roles. After LEFT JOINs, my table will look like this :

user_id - user_name          - role_name
12      - Yoda               - jedi
12      - Yoda               - master
15      - Obi-Wan Kenobi     - jedi

The first question is : How to search for users that are both "jedi" and "master". The second question is : Is it better (optimization || readability) to do it on PHP side (getting all results in an array and do some loop to verify what I want to do) or directly in the MySQL query, knowing that I will have to build the query dynamically (it's for a PHP/MySQL search engine in a great user database).

Thank you :) . user1527491

  • 写回答

1条回答 默认 最新

  • dougan1205 2013-03-03 14:06
    关注

    This problem is called RELATION DIVISION

    SELECT  a.user_name
    FROM    firstTable a
            INNER JOIN secondTable b
                ON a.user_ID = b.user_ID
            INNER JOIN thirstTable c
                ON b.role_ID = c.role_ID
    WHERE   c.role_NAME IN ('jedi', 'master')
    GROUP   BY a.user_name
    HAVING  COUNT(*) = 2
    

    If a unique constraint was not define for role_NAME for every user_name, DISTINCT keyword is needed.

    SELECT  a.user_name
    FROM    firstTable a
            INNER JOIN secondTable b
                ON a.user_ID = b.user_ID
            INNER JOIN thirstTable c
                ON b.role_ID = c.role_ID
    WHERE   c.role_NAME IN ('jedi', 'master')
    GROUP   BY a.user_name
    HAVING  COUNT(DISTINCT c.role_NAME) = 2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)