Passing a list into MySQL stored procedure and check ALL values are present

前端 未结 1 391
终归单人心
终归单人心 2021-01-29 09:21

I have a query, where I check the user has ALL the permissions present in a list of perms.

So, it\'s something like this...

SELECT DISTINCT account_id
FR         


        
相关标签:
1条回答
  • 2021-01-29 09:27

    This is what I've got so far...

    Not ideal, but you can work out the length of the items in the string with this..

    (SELECT LENGTH(permissions) - LENGTH( REPLACE(permissions, ',', '') ) + 1)
    

    It basically counts all the commas in the string and uses that as the total number of perms passed in.

    CREATE PROCEDURE has_permission( IN account_id BIGINT, IN permissions TEXT)
    BEGIN
      SELECT DISTINCT account_id
      FROM   pp_acl_user_roles ur, pp_acl_role_permissions rp
      JOIN pp_acl_permissions p ON rp.permission_id=p.id
      WHERE (
        ur.account_id = account_id
        #check for permission ids OR keys depending on what has been passed in.
        AND ( FIND_IN_SET(p.id, permissions) OR FIND_IN_SET(p.key, permissions) )
        AND ur.role_id = rp.role_id
    
      )
      #ensure we have ALL the permissions we asked for, not just some -makes IN() an AND not an OR.
      GROUP BY ur.account_id
      HAVING COUNT(DISTINCT rp.permission_id) = (SELECT LENGTH(permissions) - LENGTH( REPLACE(permissions, ',', '') ) + 1);
    
    0 讨论(0)
提交回复
热议问题