产品获取取决于使用php mysql查询的价格选择

时间:2015-06-29 10:58:11

标签: php mysql

我需要根据用户的价格选择显示产品,这里我面临的问题是我的代码请告诉我如何解决这个问题。

我创建了sql小提琴,请查看此链接clickhere

我的桌子:

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); 

当我运行这个qquery时,我的意图是产品应该出现在&#39; 6&#39;的category_id中。但在这里我也得到7分。请参阅sql fiddle中的实例。

1 个答案:

答案 0 :(得分:2)

将这个条件包装在括号中,我测试了你的小提琴

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