H
H
happ2016-05-16 21:51:09
MySQL
happ, 2016-05-16 21:51:09

Sql query to select a post and the number of likes?

It is necessary to get data from the posts and post_likes table in one query. In this case, there may be no data in post_likes. Without using JOIN, only those records are displayed where there are post_likes, using JOIN writes not unique table / alias.
post_likes structure:
CREATE TABLE post_likes (
postId INT UNSIGNED NOT NULL, /*postId - post id*/
userId INT UNSIGNED NOT NULL, /*userId - user id*/
UNIQUE KEY(postId, userId) /*combination of postId, userId must be unique*/
);
Query:
SELECT posts.id, posts.userId, COUNT(post_likes.postId)
FROM posts, post_likes
LEFT JOIN posts ON posts.id = post_likes.postId
WHERE posts.id = post_likes.postId
GROUP BY posts.id;
Help me change the request so that it works correctly.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2016-05-16
@happ

SELECT `p`.`id`, `p`.`userId`, IFNULL(`c`.`count`, 0)
  FROM `posts` AS `p`
  LEFT JOIN (
    SELECT `postId`, COUNT(*) AS `count`
      FROM `post_likes`
      GROUP BY `postId`
  ) AS `c` ON `c`.`postId` = `p`.`id`

E
evnuh, 2016-05-16
@evnuh

Do you make LEFT JOIN posts for likes?) Logically, a post may not have likes, so you need to make LEFT JOIN likes for posts. And why do you duplicate the condition in WHERE by which you have already done JOIN?
You, young man, would spend 15 minutes reading at least one article about JOIN in RDB, it would be much more useful than writing questions on a toaster.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question