使用AND和OR通过查询检索多行

时间:2015-03-18 08:46:33

标签: sql postgresql postgresql-9.1 relational-division

我想使用相同的ID来检索多行。因此,有了这个表" component_property",我想根据我的SQL查询(下面的检查)得到2条记录,id' s:8和9,但当然并且自从我和#39; m检查是否cp.property_id = 9102及更晚,并检查cp.property_id = 8801是否同时不可能。

ID;type_id;name;desc;property_id,value
--------------------------------------
8;3832;"amplifier1";"";8801;"3"
8;3832;"amplifier1";"";9102;"4015"
9;3832;"amplifier2";"";8801;"3"
9;3832;"amplifier2";"";9102;"4016"

这是我此时没有检索到的查询。

SELECT c.id, c.type_id, cp.property_id, cp.value 
FROM components_component AS c 
INNER JOIN components_componentproperty AS cp 
ON c.id = cp.component_id 
WHERE 
(cp.property_id = 9102  AND cp.value IN ('4015', '4016')) 
OR
(cp.property_id = 8801  AND cp.value = '3') 
AND c.type_id = 3832

组件===> component_property< === property

成分

id serial NOT NULL,
type_id integer NOT NULL,
name character varying(50) NOT NULL,
description character varying(255),

component_property

id serial NOT NULL,
component_id integer NOT NULL,
property_id integer NOT NULL,
value character varying(255),

属性

id serial NOT NULL,
code character varying(10),
preferred_name character varying(50),

我的预期结果是:

id;name
-------
8;amplifier1
9;amplifier2

1 个答案:

答案 0 :(得分:1)

这是关系分割的案例:

SELECT c.id, c.name
FROM   components_componentproperty cp1
JOIN   components_componentproperty cp2 USING (component_id)
JOIN   components_component         c   ON c.id = cp1.component_id
WHERE  cp1.property_id = 9102  AND cp1.value IN ('4015', '4016')
AND    cp2.property_id = 8801  AND cp2.value = '3'
AND    c.type_id = 3832
GROUP  BY c.id;

我们在这里汇集了一系列相关技术:

检查大量属性

您可以扩展上述查询,对于一个充满属性的手,它将是最快的解决方案之一。对于更大的数字,走这条路线会更方便(也开始变得更快):

5个属性的示例,根据需要展开:

SELECT c.id, c.name
FROM  (
   SELECT id
   FROM  (
      SELECT component_id AS id, property_id  -- alias id just to shorten syntax
      FROM   components_componentproperty
      WHERE  property_id IN (9102, 8801, 1234, 5678, 9876)  -- expand as needed
      GROUP  BY 1,2
      ) cp1
   GROUP  BY 1
   HAVING count(*) = 5  -- match IN expression
   ) cp2
JOIN   components_component c USING (id);

内部子查询cp1的额外步骤是必要的,因为在(component_id, property_id)中,每个components_componentproperty显然有多个条目。我们可以cp1cp2折叠成一个并检查

HAVING count(DISTINCT property_id) = 5

但我希望这会更贵,因为count(DISTINCT col)每行需要一次操作

对于很长的列表IN是一个糟糕的选择。考虑: