Tim
Tim

Reputation: 6209

SQL Query Question

I have two tables, "Messages" and "Likes" in a "test" database. The "Likes" table simply consists of two foreign keys, a "username" that points to a third table, and a "message_id" that links it to "Messages".

I want to find all the messages that have a certain value for the network_id attribute, and also return how many "Likes" each of these messages has on it. I tried doing the following query:

SELECT
`Messages`.`message_id` AS id,
`Messages`.`latitude` AS lat,
`Messages`.`longitude` AS lon,
`Messages`.`text` AS message,
`Messages`.`network_id` AS network,
`Messages`.`poster_name` AS user,
COUNT(*) AS numLikes
FROM `test`.`Messages` LEFT JOIN `test`.`Likes` on `Messages`.message_id = `Likes`.message_id
WHERE `Messages`.network_id = 2
GROUP BY
`Messages`.`message_id`,
`Messages`.`latitude`,
`Messages`.`longitude`,
`Messages`.`text`,
`Messages`.`network_id`,
`Messages`.`poster_name`
LIMIT 50;

but the problem with this is that if a message has ZERO likes on it, the numLikes on that message still has value "1". If the message has no "Likes", the message row should still be returned, but with numLikes having value 0. Can anyone point me in the right direction?

Upvotes: 0

Views: 31

Answers (2)

Johan
Johan

Reputation: 76567

Change

count(*) as numLikes

into

COUNT(likes.message_id) AS numLikes

Upvotes: 4

Nicola Cossu
Nicola Cossu

Reputation: 56357

Replace * within count() with the name of field.

Upvotes: 0

Related Questions