具有不同标准的2列的多个条件

时间:2015-11-24 17:11:25

标签: mysql

需要从表中选择需要使用具有不同条件的2列的行

CREATE TABLE IF NOT EXISTS `spec_property` (
`sp_id` int(11) unsigned NOT NULL,
  `spm_id` int(11) unsigned NOT NULL,
  `spec_value` varchar(255) NOT NULL,
  `spec_last_value` varchar(55) DEFAULT NULL,
  `product_id` int(11) unsigned NOT NULL,
  `spec_order_by` tinyint(2) unsigned DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=77 ;
ALTER TABLE `spec_property`
 ADD PRIMARY KEY (`sp_id`), ADD KEY `product_id` (`product_id`), ADD KEY `spec_value` (`spec_value`);
ALTER TABLE `spec_property`
MODIFY `sp_id` int(11) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=75;
INSERT INTO `spec_property` (`sp_id`, `spm_id`, `spec_value`, `spec_last_value`, `product_id`, `spec_order_by`) VALUES

(31, 23, 'Octa Core', NULL, 4, NULL),
(34, 26, '2048', 'MB', 4, NULL),
(35, 27, '8192', 'MB', 4, NULL),
(36, 28, '2048', 'MB', 4, NULL),
(69, 62, 'Android', NULL, 4, NULL),
(70, 63, '5', NULL, 4, NULL),
(71, 65, 'Yes', NULL, 4, NULL),
(72, 66, 'Yes', NULL, 4, NULL),
(73, 67, '32000', NULL, 4, NULL),
(74, 68, '25', 'fps', 4, NULL);

http://sqlfiddle.com/#!9/95329/13

SELECT distinct(product_id)
FROM `spec_property`
WHERE (spm_id = '62' AND spec_value IN ('Android' , 'Windows'))
    AND (spm_id = '27' AND spec_value BETWEEN 4096 AND 131072 )

如果我使用'OR'条件,我可以得到这个结果:

http://sqlfiddle.com/#!9/95329/1)。实际上我需要找到与

等过滤器选项匹配的产品ID
SELECT DISTINCT (product_id)
FROM spec_property
WHERE spm_id_62 IN ('Android', 'Windows')
    AND spm_id_27 BETWEEN 4096  AND 131072
    AND spm_id_26 BETWEEN 4096  AND 131072

1 个答案:

答案 0 :(得分:0)

您可以尝试另一组括号来构建查询

SELECT distinct(product_id)
FROM `spec_property`
WHERE ((spm_id = '62' AND spec_value IN ('Android' , 'Windows'))
OR (spm_id = '27' AND spec_value BETWEEN 4096 AND 131072 )
OR (spm_id = '26' AND spec_value BETWEEN 4096 AND 131072 ))