B
B
Bronaz7772022-03-15 19:22:10
SQL
Bronaz777, 2022-03-15 19:22:10

How to create a withdrawal request based on the number of reviews?

Help me write SQL query to complete the task
There are two tables - magazin and otziv which have fields

magazin
id|name|gorod
otziv
id|name|text|magaz_id

Task:
Display stores sorted by number of reviews - from highest to lowest id

field from magazin table associated with the magaz_id field from the otziv table. So

far, I have only managed to display them simply with sorting by id:

SELECT id,name,gorod FROM magazin WHERE gorod=$gorods ORDER BY id DESC LIMIT 20


As I understand it, you need to make a subquery with COUNT and JOIN, but it doesn’t work for me

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2022-03-15
@Bronaz777

SELECT
    magazin.id, -- укажи явно таблицу в выборке, потому что у тебя теперь есть две таблицы с полем id
    magazin.name,  -- укажи явно таблицу в выборке, потому что у тебя теперь есть две таблицы с полем name
    gorod,
    COUNT(otziv.id) AS 'qunatity' -- добавь количество отзывов в выборку. Это не обязательно, работать будет и без этого шага
FROM 
    magazin
    LEFT JOIN otziv ON (otziv.magaz_id = magazin.id) -- присоедини таблицу
WHERE 
    gorod=$gorods
GROUP BY
    magazin.id  -- добавь группировку
ORDER BY 
    COUNT(otziv.id) DESC -- поменяй сортировку
LIMIT 
    20

PS I would highly recommend never using transliterated Russian in the field names .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question