使用AND运算符

时间:2015-11-17 11:02:10

标签: mysql where-in

需要一些MySQL帮助。

我正在建立网上商店,我在使用同一列上的多个WHERE IN子句过滤搜索结果时遇到问题。

我有 shopitem 过滤器 filter_option shopitem_option

shopitem (具有名称,描述,价格等的项目)

id
title
price

过滤器(主要过滤器类别,如颜色,品牌,性别,尺寸等)

id
name

filter_option (过滤器选项,如尺寸(S,M,L),颜色(黑色,白色)等)。

id
name
filter_id (filter.id)

shopitem_option (项目和选项之间的连接)

id
shopitem_id (shopitem.id)
filter_id (filter.id)
filter_option_id (filter_option.id)

我有各种尺寸,颜色,性别等的Nike Air鞋子......

所以在 shopitem_option 表中我有以下内容:

id  |  shopitem_id  |  filter_id  |  filter_option_id
-----------------------------------------------------
1   |  Nike Air     |  Color      |  black
2   |  Nike Air     |  Color      |  white
3   |  Nike Air     |  Size       |  40
4   |  Nike Air     |  Size       |  41
5   |  Nike Air     |  Size       |  42
6   |  Nike Air     |  Gender     |  man

当我创建MySQL查询时,它需要是这样的(在纯SQL查询中而不是'黑','男'等等。有filter_option.id字段的ID )< / p>

SELECT shopitem.*
FROM shopitem
LEFT JOIN shopitem_option.shopitem_id = shopitem.id
WHERE
    shopitem_option.filter_option_id IN (black) AND 
    shopitem_option.filter_option_id IN (41,42) AND 
    shopitem_option.filter_option_id IN (man)

但这不起作用。如果我只搜索 size 40 ,或仅搜索 color black ,它将返回所有尺码为40的鞋子或所有黑色鞋子。但是,如果我将滤镜组合成搜索颜色为黑色且尺寸为40的项目,则会返回空查询结果。

所以,基本上用户可以搜索鞋子 WHERE 颜色(黑色 OR 白色) AND 尺寸(41 OR 42) AND 性别(男)。我怎么能做到这一点?

2 个答案:

答案 0 :(得分:1)

像这样使用

SELECT si.*, GROUP_CONCAT(so.filter_option_id) AS filter_options
FROM shopitem si
LEFT JOIN shopitem_option so ON(so.shopitem_id = si.id)
HAVING
FIND_IN_SET('black', filter_options)
AND  FIND_IN_SET('41', filter_options)
AND FIND_IN_SET('man', filter_options)
GROUP BY si.id

从结果中计算si.id的数量,可以像子查询一样使用

SELECT COUNT(res.id) FROM
  (SELECT si.*, GROUP_CONCAT(so.filter_option_id) AS filter_options
   FROM shopitem si
   LEFT JOIN shopitem_option so ON(so.shopitem_id = si.id)
   HAVING
   FIND_IN_SET('black', filter_options)
   AND  FIND_IN_SET('41', filter_options)
   AND FIND_IN_SET('man', filter_options)
   GROUP BY si.id) 
 AS res

答案 1 :(得分:1)

IN ... AND IN ...无法在此处工作,因为您告诉数据库选择shopitem_option,其中filter_option_id应为black41为同一记录。像这样使用EXISTS

SELECT *
  FROM shopitem i
 WHERE EXISTS (SELECT 1 FROM shopitem_option o WHERE i.id = o.shopitem_id AND o.filter_option_id IN (black))
   AND EXISTS (SELECT 1 FROM shopitem_option o WHERE i.id = o.shopitem_id AND o.filter_option_id IN (41, 42))
   AND EXISTS (SELECT 1 FROM shopitem_option o WHERE i.id = o.shopitem_id AND o.filter_option_id IN (man))