So, I'm trying to calculate the number of re-orders in my system in a restaurant. This is defined as the number of users (based on their email address, eo_email) who ordered more than once from this restaurant. Examples under the diagram
Here is a table representing my restaurants
CREATE TABLE IF NOT EXISTS `lf_restaurants` ( `r_id` int(8) NOT NULL AUTO_INCREMENT, `r_name` varchar(128) DEFAULT NOT NULL, PRIMARY KEY (`r_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ; INSERT INTO `lf_restaurants` (`eo_id`, `eo_ref_id`) VALUES ('1', 'Restaurant X'), ('2', 'Cafe Y');
And this is my order table
CREATE TABLE IF NOT EXISTS `ecom_orders` ( `eo_id` mediumint(9) NOT NULL AUTO_INCREMENT, `eo_ref_id` varchar(12) DEFAULT NOT NULL, `eo_email` varchar(255) DEFAULT NOT NULL, `eo_order_parent` int(11) NOT NULL, PRIMARY KEY (`eo_id`), ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ; INSERT INTO `ecom_orders` (`eo_id`, `eo_ref_id`, `eo_email`, `eo_order_parent`) VALUES ('', '', ' a@a.com ', '1'), ('', '', ' a@a.com ', '1'), ('', '', ' a@a.com ', '1'), ('', '', ' a@a.com ', '1'), ('', '', ' a@a.com ', '1'), ('', '', ' b@b.com ', '1'), ('', '', ' b@b.com ', '1'), ('', '', ' c@c.com ', '1'), ('', '', ' d@d.com ', '1'), ('', '', ' e@e.com ', '1'), ('', '', ' a@a.com ', '2'), ('', '', ' c@c.com ', '2'), ('', '', ' c@c.com ', '2'), ('', '', ' e@e.com ', '2');
So, restaurant X (r_id 1) has 10 orders. Users a@a.com and b@b.com ordered at this restaurant several times, and c@c.com , d@d.com and e@e.com only ordered once, so it will need to return 40%
Cafe Y (r_id 2) has 4 orders. The user c@c.com ordered twice, the users a@a.com and e@e.com only ordered once, so he would need to return 33%
I'm not sure that posting what I already have will be very good, because I continue to work in “Subquery has more than one result” or if I wrap this subquery in my own dummy query with count, this will not allow me to use fields that I need from a main request like r_id. But here goes:
SELECT r_name, (SELECT COUNT(*) AS cnt_users FROM ( SELECT * FROM ecom_orders WHERE eo_order_parent = r_id GROUP BY eo_email ) AS cnt_dummy ) AS num_orders, (SELECT COUNT(*) AS cnt FROM ecom_orders WHERE eo_order_parent = r_id GROUP BY eo_order_parent, eo_email ) AS num_rep_orders FROM lf_restaurants ORDER BY num_orders DESC
The subquery num_orders says that it does not recognize r_id, as I assume this is related to the order of things
The num_rep_orders subquery is returned as multiple lines, but in fact I want this to return with only one value, which I could do if I made it as a num_orders subquery, but then ran into r_id, and there is no problem.
So my question is: how do I get these values that I need, without starting into a subquery, have more than 1 row, and r_id does not exist?
Then from these two values I can work out a percentage, and everything should be genuine :) Any help is greatly appreciated!