简体   繁体   中英

Products fetching depend on price selection using php mysql query

I need to display products depend on price selection by user, here I am facing issue here is my code please tell me how to solve this.

I have created sql fiddle please check this link clickhere

My tables:

CREATE TABLE products (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(500) NOT NULL,
  `description` text NOT NULL,
  `category_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

INSERT INTO products (`id`, `name`, `description`, `category_id`) VALUES 
(1, 'Samsung Galaxy S4', 'Samsung Galaxy S4 GT- I9500', 6),
(2, 'Samsung Galaxy S3 Neo', 'Samsung Galaxy S3 Neo', 6),
(3, 'Samsung Galaxy S Duos 3', 'Samsung Galaxy S', 6),
(4, 'Samsung Galaxy Grand 2', 'Samsung Galaxy Grand 2', 6);

INSERT INTO products (`id`, `name`, `description`, `category_id`) VALUES 
(5, 'Samsung Galaxy TAB', 'Samsung Galaxy TAB', 7),
(6, 'Samsung Galaxy TAB 2', 'Samsung Galaxy TAB 2', 7),
(7, 'Samsung Galaxy TAB 3', 'Samsung Galaxy TAB 3', 7),
(8, 'Samsung Galaxy TAB 4', 'Samsung Galaxy TAB 4', 7);

CREATE TABLE price (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `price` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

INSERT INTO price (`id`, `product_id`, `price`) VALUES
(1, 1, 6930),
(2, 1, 7000),
(3, 2, 12490),
(4, 2, 13000),
(5, 3, 6400),
(6, 3, 7000),
(7, 4, 14300),
(8, 4, 15000),
(9, 5, 10000),
(10,5, 11000),
(11,6, 12000),
(12,6, 13000),
(13,7, 14000),
(14,7, 15000),
(15,8, 20000),
(16,8, 22000);

select DISTINCT p.*, p.category_id as pid FROM products AS p LEFT JOIN price as pr ON pr.product_id=p.id where pr.price >= 5001 AND pr.price <= 10000 OR pr.price >= 10001 AND pr.price <= 20000 AND p.category_id IN (6); 

When I run this qquery my intention is products should come with in the category_id of '6' but here I am getting 7 also. please see live example in sql fiddle.

只需将此条件放在括号中,我已经测试了您的小提琴

where (pr.price >= 5001 AND pr.price <= 10000 OR  pr.price >= 10001 AND pr.price <= 20000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM