选择所有匹配的连接

时间:2013-09-16 22:26:10

标签: sql

表:

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用HAVING和条件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

答案 2 :(得分: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