Answer the question
In order to leave comments, you need to log in
Logical error of joining tables
Good afternoon!
There are two tables:
objects
id | title | active | rating
comments
id | obj_id | text
We need to extract all objects and the number of comments for each.
I form a request:
SELECT `objects`.*, count(comments.obj_id) AS `comments`
FROM `objects`
LEFT JOIN `comments` ON objects.id = comments.obj_id
WHERE objects.active = 1
GROUP BY `comments`.`obj_id`
ORDER BY `objects`.`rating` DESC
LIMIT 1000
SELECT `objects`.* AS `comments`
FROM `objects`
WHERE objects.active = 1
ORDER BY `objects`.`rating` DESC
LIMIT 1000
Answer the question
In order to leave comments, you need to log in
What if it's straight forward?
SELECT `objects`.*, COUNT(SELECT `id` FROM `comments` WHERE `objects`.`id` = `comments`.`obj_id`) AS `comments`
FROM `objects`
WHERE `objects`.`active` = 1
ORDER BY `objects`.`rating` DESC
LIMIT 1000
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question