2

I have a query on a Left join, where the Table who joins can contain zero rows. The problem is that if I select from that, then there are no rows where the join table contains zero rows. How can I select it then anyway?

Here is my query

SELECT server.id
    , COALESCE( AVG( playerData.player ) , 0 ) AS average 
FROM server 
LEFT JOIN playerData ON server.id = playerData.serverID 
    AND (playerData.timestamp > UNIX_TIMESTAMP( ) -10000)

The playerData table stores in one row how many people were on a server on a specific time. And multiple rows of this needs to be calculated to an average and this needs to be joined to the other query. When I omit the secound select column it gives me all rows (like it should), otherwise it only shows a result where also appropriate rows in the playerData table exists.

Additional Table data: playerData Table:

playerData table

For the other table only the id column is important in this case.

3
  • 1
    it would be great knowing table structures! Commented May 22, 2013 at 20:04
  • Your description is not clear. Please consider providing some sample data and the desired output. Commented May 22, 2013 at 20:11
  • 1
    Please note that you are mixing non-aggregated and aggregated columns in a query without GROUP BY. Commented May 22, 2013 at 20:15

1 Answer 1

2

Try this:

SELECT server.id
    , COALESCE( AVG( playerData.player ) , 0 ) AS average 
FROM server 
LEFT JOIN playerData ON server.id = playerData.serverID 
    AND (playerData.timestamp > UNIX_TIMESTAMP( ) -10000)
group by server.id

Your query is missing the group by clause. When you include an aggregation function (like AVG()), the query automatically becomes an aggregation query. Without group by, all rows are aggregated into a single row. Presumably, you want one row per server.id.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that was the problem. (But I try to add additional Information to my Question anyways as suggested in the comments, for people who have the same problem)
It make sense now. If I use aggregate function in sub-query will it still consider aggregation query for outer one?

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.