0

桌子 :

CREATE TABLE product_option
(
  id bigint NOT NULL,
  option_type character varying(255) NOT NULL,
  value character varying(255) NOT NULL,
  product_id bigint,
  CONSTRAINT product_option_pkey PRIMARY KEY (id ),
  CONSTRAINT fk_product FOREIGN KEY (product_id)
      REFERENCES product (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)

用户可以搜索具有选项列表的产品。即查找具有这些选项的产品:

BINDING_SIDE : BOTTOM
BINDING_SIDE : TOP
BINDING_TYPE : COIL_BINDING

结果应该只返回至少具有这三个选项的产品。(他们可以有更多选择)

4

3 回答 3

1

option_type, value如果您可以有重复的组合,这将不起作用:

Select
    Product_id
From
    Product_Options
Where
    (Option_Type = 'BINDING_SIDE' and value = 'BOTTOM') Or
    (Option_Type = 'BINDING_SIDE' and value = 'TOP') Or
    (Option_Type = 'BINDING_TYPE' and value = 'BOTTOM') Or
Group By
    Product_id
Having
    Count(*) >= 3
于 2013-09-16T22:44:08.193 回答
0

你可以使用HAVINGand 一个条件SUM()来得到这个:

SELECT product_id
FROM YourTable
GROUP BY product_id
HAVING   SUM(CASE WHEN option_type = 'BINDING_SIDE' AND value = 'BOTTOM' THEN 1 ELSE 0 END) >= 1
     AND SUM(CASE WHEN option_type = 'BINDING_SIDE' AND value = 'TOP' THEN 1 ELSE 0 END) >= 1
     AND SUM(CASE WHEN option_type = 'BINDING_TYPE' AND value = 'COIL_BINDING' THEN 1 ELSE 0 END) >= 1
于 2013-09-16T22:35:36.153 回答
0

试试这个代码

 SELECT product_id 
FROM product
group by product_id
having SUM(
    (case when (option_type = 'BINDING_SIDE' and value = 'BOTTOM') then 1 else 0 end)
   + (case when (option_type = 'BINDING_SIDE' and value = 'TOP') then 1 else 0 end)
   + (case when (option_type = 'BINDING_SIDE' and value = 'COIL_BINDING') then 1 else 0        end)
      ) >=3
于 2013-09-16T22:53:15.090 回答