mysql - 使用两个 where 子句过滤结果

标签 mysql sql

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

1 - Option

2 - Type

这是我针对这种类型的表格:

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

属性选项:

 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 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN property_option ON property.PropertyNumber = property_option.Property' at line 9

最佳答案

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

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

关于mysql - 使用两个 where 子句过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32188573/

相关文章:

python - 尝试通过 python 插入时出现 SQL 语法错误

mysql - 选择 POINT() 100 米半径范围内的所有点

sql - 为什么 ADODB 在更新时插入 NULL 值?

SQL 删除编号最小的重复行

sql - 如何检查记录是否存在于另一个表中,如果不存在则添加

mysql - 使用 mysql LEFT Join DESC 命令不起作用

mysql - 如果空显示0,如何按列选择行计数组

android - (Android) 不断收到 SQL 语句错误

php - 如何计算PHP中变量的总和

sql - 更改要计算的列 SQL SERVER