سؤال

I am learning databases and I'm hitting an issue and I want someone to explain it to me. I have a table.

car     | car_id | car_type
________________________________
bmw     |   1    | <bmwcartype1>
bmw     |   1    | <bmwcartype2>
bmw     |   1    | <bmwcartype3>
bmw     |   1    | <bmwcartype4>
mercedes|   2    | <mercedescartype1>
mercedes|   2    | <mercedescartype2>
mercedes|   2    | <mercedescartype3>
lexus   |   3    | <lexuscartype1>
lexus   |   3    | <lexuscartype2>
lexus   |   3    | <lexuscartype3>
lexus   |   3    | <lexuscartype4>
lexus   |   3    | <lexuscartype5>

I want to display for example the car and the number of cartypes. I'm not sure how to explain this but on the table above I only managed to get the first row.

SELECT car, COUNT(car) AS number_of_cars FROM cars WHERE car_id = 1

This is displaying the first row like:

car | number_of_cars
bmw |   4

And I want the following rows to be:

car      | number_of_cars
bmw      | 4
mercedes | 3
lexus    | 5

How can I do that?

هل كانت مفيدة؟

المحلول

You have an aggregation query that returns one row. Just as a note, this query works in MySQL but would fail in most databases. The column car is not in a group by. Even though you are choosing only one value, SQL engines don't usually allow this (MySQL is an exception).

The query that you want is:

SELECT car, COUNT(car) AS number_of_cars
FROM cars
group by car;

Note that car appear both in the select and group by. Although you could have car_id in the group by. this is bad form. Try to be sure that the unaggregated columns in the select are always in the group by -- at least until you really understand what you are doing with SQL.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top