E
E
EvgMul2021-06-23 17:01:26
MySQL
EvgMul, 2021-06-23 17:01:26

What is wrong with my request?

Hello. I need to know the number of related records in two tables. I got the following query:

select
       main.id
       count(news.id) as news,
       count(articles.id) as articles
from main
    LEFT JOIN news ON main.id = news.main_id
    LEFT JOIN articles ON articles.id = articles.main_id
group by main.id
order by news desc;


As a result, I get the values ​​​​in the fields newsand articlesmultiplied by each other.
If I make two requests for one join, then I get the correct data. Tell me, please, what is my mistake?
Thanks in advance to all who respond.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-06-23
@EvgMul

SELECT main.id,
       ( SELECT COUNT(*) 
         FROM news 
         WHERE main.id = news.main_id ) news,
       ( SELECT COUNT(*) 
         FROM articles
         WHERE main.id = articles.main_id ) articles
FROM main
ORDER BY news DESC;

Main(id) is supposed to be a unique field (most likely a primary key).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question