Answer the question
In order to leave comments, you need to log in
How to select one line from each condition?
Good afternoon, I study sql, there was a task.
There is a table in which categories are stored, id, parent_id, name.
Suppose the category is: Cars, and its subcategories are: Electric, Gasoline.
Cars: parent_id - 0
Electric: parent_id - (id "cars")
Gasoline
: parent_id - (id "cars"
)
branch.
There is a "Cars.php" page, on it you need to display 1-2 cars from each subcategory, "Cars" category.
Those. the response to the request should be 2-4 (we will set the LIMIT ourselves later) lines from gasoline and electric.
Answer the question
In order to leave comments, you need to log in
SELECT t1.id, Автомобили.name, t1.category_id from
(
SELECT MAX(id) as id, category_id FROM Автомобили WHERE category_id IN
(SELECT id FROM Категории WHERE parent_id = 0)
GROUP BY category_id
) t1 left join Автомобили on Автомобили.id = t1.id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question