Answer the question
In order to leave comments, you need to log in
Nested SQl query, how to make it right?
Good day.
Task:
Get the number of likes and subscriptions in one request.
Follows and likes are stored in a many-to-many relationship.
I made separate requests that receive the number of likes and subscriptions separately.
For likes it turned out like this:
select count(user_idea_likes.idea_id) as likes from `articles` inner join `user_article_likes` on `user_article_likes`.`article_id` = `articles`.`id` group by `articles`.`id`;
For subscriptions, it turned out like this:
select count(subscribed_user_articles.article_id) as subscribed from `articles` inner join `subscribed_user_articles` on `subscribed_user_articles`.`article_id` = `articles`.`id` group by `articles`.`id`;
From all this I want to get just one request with the output:
Article
- number of likes
- number of subscriptions
(well, so on each article)
Any ideas? Thoughts? Where to look and what to read?
Answer the question
In order to leave comments, you need to log in
Idea to play:
select
article_id,
count(distinct user_article_likes.article_id),
count(distinct subscribed_user_articles.article_id)
from articles
left join лайки
left join подписки
group by article
Two separate ones are easier.
It just needs to be simplified.
If for one article, then:
If for everyone, then:
SELECT article_id, COUNT(*) FROM user_idea_likes GROUP BY article_id
Have you tried just merging?
Used left join for data completeness.
SELECT `articles`.`id`, count(user_idea_likes.idea_id) AS likes,
count(subscribed_user_articles.article_id) AS subscribed
FROM `articles`
LEFT JOIN `user_article_likes` ON `user_article_likes`.`article_id` = `articles`.`id`
LEFT JOIN `subscribed_user_articles` ON `subscribed_user_articles`.`article_id` = `articles`.`id`
GROUP BY `articles`.`id`
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question