This is a question regarding queries in mysql. As an example let’s use a system that tracks the selling of cars. There is table with salespersons, a table of sales and a table that links the two. Most of the time each sale has only one person associated with it. But sometimes multiple persons are associated with a sale.
Table sales
id | carId | date
---+-------+-----------
1 | 2 | 11-01-2011
2 | 8 | 11-02-2011
3 | 5 | 11-05-2011
Table link
personId | saleId
---------+-------
2 | 1
2 | 2
1 | 3
2 | 3
Table salesperson
id | name | age
---+-------+----
1 | Barry | 25
2 | Sara | 32
To retrieve the data I want to show the information of each sale in a webpage. But when multiple persons are associated with a sale it becomes problematic. I have tried applying the query below in my code, after which the PHP handles the exception of when multiple persons are associated with one sale, but due to the length of the sales table the query below takes too much time to run:
SELECT count(personId) as amount, carId, date
FROM link
JOIN salesperson ON link.personId = salesperson.id
JOIN sales ON sales.id = link.saleId
GROUP BY link.saleId
Is there a more efficient query that can be used? By the way indexing of the table is already done.
Then it is just: