Answer the question
In order to leave comments, you need to log in
Have I created the sql query correctly?
There are such tables:
Users table – site user:
SELECT users.name from users
INNER JOIN articles ON (articles.user_id = users.id)
INNER JOIN comments ON (comments.user_id = users.id)
GROUP BY users.name;
Answer the question
In order to leave comments, you need to log in
No, the request was made incorrectly! He, in addition to what is required, will also select users who wrote a comment, even if no one commented on their own articles ... not to mention that if there is no explicit need to aggregate fields in a group, then using GROUP BY there , where you can get by with DISTINCT - an expensive pleasure (why - I'll explain further, but for now, just for comparison, its plan and "cost"):
To just get the desired result, of course, you can stupidly supplement it with another JOIN with article_comment_association , but this still very bad: firstly, JOIN with a table of comments is simply superfluous there, and secondly, GROUP BY is still the same waste of resources:
Here, for comparison, the cost of DISTINCT vs. GROUP BY:
(I will not give all these incorrect options, so that they are not accidentally copied into the nuclear reactor control system!)
In this sense, the option proposed by Rsa97 is already better, because gives the correct result.
SELECT name FROM users
WHERE id IN (
SELECT user_id FROM article
WHERE id IN (
SELECT article_id FROM article_comment_association
)
);
SELECT distinct users.name from users
INNER JOIN article ON (article.user_id = users.id)
INNER JOIN article_comment_association ON (article.id = article_comment_association.article_id)
SELECT `name`
FROM `users`
WHERE `id` IN (
SELECT `user_id`
FROM `article`
WHERE `id` IN (
SELECT `article_id`
FROM `article_comment_association`
)
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question