过滤结果中包含两个where子句

时间:2015-08-24 17:52:07

标签: mysql sql

我想使用两个类型的多重复选框来过滤属性:

  

1 - 选项

     

2 - 输入

以下是此类型的表格:

propety_type

CREATE TABLE IF NOT EXISTS `property_type` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `PropertyNumber` int(4) NOT NULL,
    `TypeNumber` int(50) NOT NULL,
     PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=25 ;

INSERT INTO `property_type` (`ID`, `PropertyNumber`, `TypeNumber`) VALUES
(13, 53, 1),
(14, 53, 2),
(15, 53, 3),
(16, 54, 3),
(17, 54, 5),
(18, 55, 6),
(19, 55, 8),
(20, 56, 3),
(21, 56, 2),
(22, 56, 1),
(23, 54, 1),
(24, 55, 1); 

property_option

 CREATE TABLE IF NOT EXISTS `property_option` (
   `ID` int(11) NOT NULL AUTO_INCREMENT,
   `PropertyNumber` int(11) NOT NULL,
   `OptionNumber` int(11) NOT NULL,
   PRIMARY KEY (`ID`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=53 ;


INSERT INTO `property_option` (`ID`, `PropertyNumber`, `OptionNumber`) VALUES
(35, 53, 1),
(36, 53, 2),
(37, 53, 3),
(39, 54, 3),
(40, 54, 5),
(41, 55, 6),
(42, 55, 8),
(43, 56, 2),
(45, 56, 1),
(46, 56, 3),
(47, 56, 8),
(48, 53, 9),
(49, 53, 4),
(50, 55, 1),
(51, 54, 2),
(52, 54, 1);

我的查询:

SELECT property.PropertyNumber 
FROM property
INNER JOIN property_option ON property.PropertyNumber = property_option.PropertyNumber 
WHERE property_option.OptionNumber IN (1,3 ) 
GROUP BY property.PropertyNumber 
HAVING COUNT(DISTINCT property_option.ID) =2 
INNER JOIN property_type ON property.PropertyNumber = property_type.PropertyNumber 
WHERE property_type.TypeNumber IN (1,2 ) 
GROUP BY property.PropertyNumber 
HAVING COUNT(DISTINCT property_type.ID) =2 

但是当我在phpmyadmin中测试时,我收到此错误:

  

#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在第9行的'INNER JOIN property_option ON property.PropertyNumber = property_option.Property'附近使用正确的语法

1 个答案:

答案 0 :(得分:0)

如果要确保返回的行满足同时具有指定选项和两种指定类型的要求,则可以使用下面的查询。

SELECT p.PropertyNumber
FROM property p
JOIN property_option  USING (PropertyNumber)
JOIN property_type    USING (PropertyNumber)
WHERE OptionNumber IN (1,8) 
  AND TypeNumber   IN (1,2) 
GROUP BY p.PropertyNumber 
HAVING COUNT(DISTINCT OptionNumber) = 2 
   AND COUNT(DISTINCT TypeNumber)   = 2;

Sample SQL Fiddle