0

I have 3 tables :

Role :

id name user_id
1 president 1
2 chief 1
3 caporal 1
4 president 2
5 caporal 3

Group :

id name user_id
1 test1 1
2 test2 3
3 test3 1
4 test1 2
5 test3 2

User

id username
1 user1
2 user2
3 user3

I would like to select all group with a field condition : if userX have more than 0 role and if in these roles it has 'president' then return 1 otherwise 0.

So having data like this :

user_id username role_condition group_name
1 user1 1 test1
1 user1 1 test3
2 user2 1 test1
2 user2 1 test3
3 user3 0 test2

I tried this :

SELECT u.id,
       u.username,
       if(LOCATE('president', group_concat(u.role)) > 0,1,0),
       g.name
FROM Group g
LEFT JOIN User u ON u.id = g.user_id
LEFT JOIN Role r ON r.user_id = u.id

Without a group by it gives me only 1 row because of the group_concat, and I can't use the group by because if I do that on user_id or username it will not give me all the rows I want.

I don't know how to do that and having the result I want.

Thank for your help :)

4
  • What version of MySQL are you using? Commented Jan 19, 2021 at 16:06
  • The normalization looks a little weird. The group ids 1 and 4 are both "test1" the name in the role table is massively redundant .... And i do not really understand the desired outcome :-( Commented Jan 19, 2021 at 16:09
  • @PhilCoulson 5.7 Commented Jan 20, 2021 at 14:31
  • @AlexanderDobernig Yes i could use an other name, the customer wants to have a result I wrote, it's just the last collumn who change 'group_name' Commented Jan 20, 2021 at 14:35

1 Answer 1

1

You can do it without aggregation, with EXISTS:

SELECT u.id, u.username,
       EXISTS (
         SELECT 1 FROM Role r
         WHERE r.user_id = u.id AND r.name = 'president'
       ) role_condition, 
       g.name
FROM `User` u INNER JOIN `Group` g
ON g.user_id = u.id
ORDER BY u.id

If you want all the users, even those without any group, change to a LEFT join.

See the demo.
Results:

id username role_condition name
1 user1 1 test1
1 user1 1 test3
2 user2 1 test1
2 user2 1 test3
3 user3 0 test2
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for the answer, it works well in local but on the customer server it gave me a 500, because in my request I had to to lot of exist (idk if it's the version of mysql 5.7)
@pham01 my query works for the requirement as you described it in your question and it provides your expected results. I can't say why you get a 500 error in the Mysql server.
Please look into the server error log where you will find the exact error message resulting in the Error500 message. Post the error and the code where the error occurred and you may be helped
@AlexanderDobernig Yes it's a memory limit error
Please tell us the complete error line
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.