mysql - Fixing SQL Query so it will become more Efficient -
i've got 3 tables:
mobile_users
-id
,phone_type
,...
2+3. iphone_purchases
, android_purchases
- id
,status
,user_id
,..
i trying of users made 2 or more purchases. successful purchase identified status > 0
. tring total amount of users in mobile_users
table in same query.
this query came with:
select count(*) `users`, ( select count(*) `mobile_users` ) `total` `mobile_users` `mobile_users`.`phone_type` = 'iphone' , ( select count(*) ( select `status`, `user_id` `iphone_purchases` union select `status`, `user_id` `android_purchases` ) `purchase_list` `purchase_list`.`status` > 0 , `purchase_list`.`user_id` = `mobile_users`.`id` ) >= 2
it's slow, , have find way improve it. appreciated!
edit: should take in consideration i'm building query sub-queries in php. i'm building more conditions on statment.
your query returning counts of users, not each user.
the following restructures query. counts number of purchases iphones , androids separately, , combines them using left outer join
. where
clause combines counts:
select mu.*, i.cnt iphones, a.cnt androids mobile_users mu left outer join (select `user_id`, count(*) cnt `iphone_purchases` `status` > 0 group user_id ) on i.user_id = mu.id left outer join (select `user_id`, count(*) cnt `android_purchases` `status` > 0 group user_id ) on a.user_id = mu.id coalesce(i.cnt, 0) + coalesce(a.cnt, 0) >= 2;
Comments
Post a Comment