1

I’m developing an app. I have to do a query where I see the rooms where I’m guest or admin. That's easy. The problem is that I want to get, at the same time, the number of players inside the same room.

SELECT rooms.id, rooms.name, rooms.buyin, rooms.administrator, rooms.creation_date,
       rooms.max_players, rooms.min_players, count(room_players.room)
FROM rooms, room_players
WHERE administrator = 1 and room_players.room = rooms.id 

I have a table with the rooms and the other (room_players) that is a match between users and rooms. If i delete the count(room_players.room) and and room_players.room = rooms.id I have the rooms that I’m admin. But I need the number of players inside the same room too.

2 Answers 2

5

Your query needs a group by. With the COUNT() in the select, it becomes an aggregation query that returns one row -- a summary of all the rows in the table.

SELECT r.id, r.name, r.buyin, r.administrator, r.creation_date,
       r.max_players, r.min_players, count(rp.room)
FROM rooms r join
     room_players rp
     ON rp.room = r.id 
WHERE administrator = 1 
GROUP BY r.id;

I also fixed the join syntax to be an explicit join and added table aliases to make the query more readable.

EDIT:

I suspect the query you want is something like:

SELECT r.id, r.name, r.buyin, r.administrator, r.creation_date,
       r.max_players, r.min_players, count(rp.room)
FROM rooms r join
     room_players rp
     ON rp.room = r.id 
WHERE administrator <> 1 
GROUP BY r.id
HAVING sum(user = 1) > 0;
Sign up to request clarification or add additional context in comments.

4 Comments

It did work. Many thanks. I tried to join two queries, but didn't work and I don't know why. I liked your way, it's easier and simple to understand.
But i have a problem with this, if i want to get the rooms that I'm not admin (only guest), it doesn't counts very well the number of players inside the room.
@miguelpveloso . . . I don't know what admin is. If it is a column in room_players, then you can remove the where and after the group by: having sum(administrator = 1) > 0.
SELECT r.id, r.name, r.buyin, r.administrator, r.creation_date, r.max_players, r.min_players, count(rp.room) FROM rooms r join room_players rp ON rp.room = r.id WHERE administrator != 1 AND rp.user = 1 GROUP BY r.id; Is this possible? This doesn't return me the count of players inside the room.
0

How about subtracting the # of admin from the total users?

1 Comment

Wouldn't hurt to use GROUP BY or even, universe-forbid, naming fields the same in different tables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.