S
S
stainer2018-08-14 14:29:51
MySQL
stainer, 2018-08-14 14:29:51

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

1 answer(s)
A
Alex, 2018-08-14
@streetflush

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

If without crutches, then it’s realistic to choose 1st.
Not sure if MySQL syntax works, but MSSQL should

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question