Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select value based on role

The following results from a temp table.
Please Note : The data below is just a sample so I don't need a hardcoded query, I need a query which works for all kinds of data.

Value = 1 means the User has the role and 0 means the user has no role. Like row one Testing 1 has Role A but not Role D.

I need a query for the below cases.

Case # 1 when Role ID = ( A,B,C,D ) I only need the user/s which have atleast one role assigned. I should get back User Testing 1, Testing 2 and Testing 3. Testing 4 wont be coming as no role has been assigned to it.

Case # 2 When Role ID = ( A,B,C,D ) . I only need the user/s which have all the roles assigned to a it. I should get User Testing2 with 4 rows.

username Value Role ID
Testing1 1 A
Testing1 1 B
Testing1 1 C
Testing1 0 D
Testing2 1 A
Testing2 1 B
Testing2 1 C
Testing2 1 D
Testing3 1 A
Testing3 1 B
Testing3 1 C
Testing3 0 D
Testing4 0 A
Testing4 0 B
Testing4 0 C
Testing4 0 D

like image 332
Ally Avatar asked Sep 04 '26 08:09

Ally


1 Answers

CASE # 1 (which have atleast one role assigned)

SELECT b.*
FROM   
    (
      SELECT DISTINCT [username], Value
      FROM tableName
      WHERE value = 1
    ) a
      INNER JOIN TableName b
        ON a.username = b.username
WHERE  a.value = 1

SQLFiddle Demo

CASE # 2 (which have all the roles assigned to a it)

SELECT username
FROM tableName
WHERE RoleID IN ('A','B','C','D')
GROUP BY username
HAVING COUNT(DISTINCT roleID) = 4

SQLFiddle Demo

like image 107
John Woo Avatar answered Sep 06 '26 19:09

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!