I have the following tables:
customers
cus_id
(primary key)driver_licence_id
(int UNIQUE)
cars
car_id
(primary key)cus_id
(foreign key tocustomer
and suggests that this customer owners this car)date_created
(datetime)
parts (different parts of a car, eg, engine, spark plugs etc)
part_id
(primary key)manufacturers_id
(int)
parts_in_car (Which parts are in the car)
part_in_car_id
(primary key)car_id
(foreign key tocar
table)part_id
(foreign key toparts
table)
I am essentially trying to grab a concatenated string of all the manufacturers_id
which is in a car which is owned by a specific driver_licence_id
. The following SQL query works as I want it to however it takes over 1 second
to execute. I have over 1 million total rows. The query I tested with results 20 rows.
SELECT GROUP_CONCAT(p.manufacturers_id ORDER BY p.manufacturers_id) as mids
FROM car c INNER JOIN
parts_in_car pic
ON c.car_id = pic.car_id JOIN
parts p
ON pic.part_id = p.part_id JOIN
customers cus
ON c.cus_id = cus.cus_id
WHERE cus.driver_licence_id = 5555555
group by c.car_id, c.date_created
ORDER BY c.date_created
I tried doing the following indexes for the sole purpose of this query. Can someone tell me what indexes to create.
# Customer
CREATE INDEX customer_driver_licence_id_idx
ON customer (driver_licence_id);
# cars
CREATE INDEX cars_cus_id_idx
ON cars (cus_id);
# parts
CREATE INDEX parts_manufacturers_id_idx
ON parts (manufacturers_id);
# parts_in_car
CREATE INDEX parts_in_car_part_id_idx
ON parts_in_car (part_id);
CREATE INDEX parts_in_car_car_id_idx
ON parts_in_car (car_id);
Update: The problem is the group by
and I already indexed (car_id, date_added) to try solve the problem
#EXPLAIN SELECT
+-------+-------------------------------------+
| table | key |
+-------+-------------------------------------+
| a | cus_id |
| o | cars_cus_id_car_id_date_created_idx |
| pip | parts_in_car_car_id_idx |
| p | PRIMARY |
+-------+-------------------------------------+