D
D
Denis2012-11-03 12:33:33
MySQL
Denis, 2012-11-03 12:33:33

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

But not all records are returned. Returns 16 rows

A query:
SELECT `objects`.* AS `comments`
FROM `objects`
WHERE objects.active = 1 
ORDER BY `objects`.`rating` DESC 
LIMIT 1000

27 lines

What is my mistake here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2012-11-03
@newpdv

need GROUP BY `objects`.`id`

N
Nazar Mokrinsky, 2012-11-03
@nazarpc

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 question

Ask a Question

731 491 924 answers to any question