php - Which MySQL Query to Select Product Based on Location -
basic scenario: have 3 types of product, several manufactures , based on customer's location, product comes closest manufacture. have works think tables need structured little better.
here have currently:
create table if not exists `mfr` ( `id` int(11) not null auto_increment, `zip_code` int(5) not null, `radius` int(5) not null, primary key (`id`) ) engine=innodb default charset=latin1 auto_increment=8 ; insert `mfr` (`id`, `zip_code`, `radius`) values (1, 72756, 500), (2, 74030, 360), (3, 74701, 325), (4, 72947, 300), (5, 73112, 40), (6, 63077, 100), (7, 63106, 75); create table if not exists `models` ( `id` int(11) not null auto_increment, `name` varchar(50) not null, `mfr_id` int(5) not null, primary key (`id`) ) engine=innodb default charset=latin1 auto_increment=8 ; insert `models` (`id`, `name`, `mfr_id`) values (1, 'model 1', 1), (2, 'model 2', 2), (3, 'model 3', 2), (4, 'model 1', 6), (5, 'model 2', 4), (6, 'model 3', 4); create table if not exists `distances` ( `id` int(11) not null auto_increment, `time_inserted` int(11) not null, `zip_code` int(5) not null, `mfr_id` int(5) not null, `miles` int(5) not null, primary key (`id`), key `zip_code` (`zip_code`) ) engine=innodb default charset=utf8 collate=utf8_unicode_ci auto_increment=16 ; insert `distances` (`id`, `time_inserted`, `zip_code`, `mfr_id`, `miles`) values (1, 1397522155, 72761, 1, 41), (2, 1397522155, 72761, 2, 131), (3, 1397522155, 72761, 3, 223), (5, 1397522155, 72761, 5, 197), (6, 1397522156, 72761, 6, 301), (7, 1397522156, 72761, 7, 353), (8, 1397522166, 72761, 4, 87); expected result: zip code of 72761 should return mfr_id of 1 model 1 41 miles, mfr_id of 4 models 2 , 3 miles of 87, instead mfr_id of 2 returned models 2 , 3, though milage 131, greater 87.
try this:
select m.name, d.miles, d.mfr_id distances d join mfr on mfr.id = d.mfr_id , mfr.radius > d.miles join models m on m.mfr_id = mfr.id -- min miles per model join (select m1.name,min(d1.miles) miles models m1 join distances d1 on d1.mfr_id = m1.mfr_id group m1.name ) md on md.name = m.name , md.miles = d.miles d.zip_code = 72761 order d.miles asc
Comments
Post a Comment