S
S
suhuxa12017-09-02 23:00:08
MySQL
suhuxa1, 2017-09-02 23:00:08

How to form such a sql query correctly?

There are 2 tables in the database. One contains cars. And in the second spare part to it.
First type: 1 | BMW 2 | AUDI..etc. That is, id + name
Second type: 1 | Mirrors, 1 | Blocks, 1 | Bumper, 2 | Wheels
I greatly simplified everything, but the bottom line is that spare parts have a car ID. So, in one query, I need to select all cars from 1 table + for each of them, find out the number of spare parts from the second. Just quantity and that's it. How to form this?
I wrote something like this:

SELECT auto.*, count(parts.id) as total FROM auto LEFT JOIN parts ON auto.id = parts.auto_id

Alas, it didn't work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2017-09-02
@suhuxa1

It is necessary to group records by car brand:

SELECT auto.*, count(parts.id) as total
FROM auto
LEFT JOIN parts ON auto.id = parts.auto_id
GROUP BY auto.id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question