Reputation: 323
How I can optimize a triple join query like this
select users.id_user from users,sales,specSales where users.id_user=sales.id_user AND sales.id_sale=specSales.id_sale AND specSales.id_article=34 group by id_user
I want distinct users who bought the product identified by the id_article=X
i've thought to this but I'm not secure of the improvement
select id_user from (select distinct(sales.id_user) from sales,specSales where sales.id_sale=specordine.id_sale and specSale.id_article=34)as t
tables are ( *=primary key)
users
*id_user | name | ....
sales
*id_sale | id_user | .... other values
salesSpec
id_sale | id_article | .... other values
Lots of Thanks
Upvotes: 2
Views: 1646
Reputation: 1270713
The second query can be simplified to:
select distinct(sales.id_user)
from sales join
specSales
on sales.id_sale=specordine.id_sale
where specSale.id_article=34
This should perform faster than the first version. One simple reason: it is not joining in the users table. The "distinct" should be about the same amount of work as the "group by", so the difference in joins should be the dominant effect for performance.
This assumes that the joining of the users table did not act as a filter (all user ids ain sales are in the table and there are no duplicates).
Also, you should start using proper join syntax. The use of the "," in the from statement is bad practice.
Upvotes: 2