复杂的SQL查询

时间:2015-07-07 07:34:20

标签: sql postgresql jointable

我继承了一个拥有产品的数据库,其中每个产品都有属性,这些属性按组进行组织,

我需要构建一个查询,允许用户指定一堆属性并返回每个组中至少有一个匹配项的产品。

因此,如果产品的颜色为蓝色,则尺寸:xl和collarshape是vneck, 并且用户选择蓝色,绿色,vneck xl xxl,然后上述产品将匹配。如果产品只有黄色,则不匹配

下面是表结构..

E.g。颜色:蓝色,黄色,绿色,尺寸:xl xxl l s,collarshape:vneck,crewneck

\ the products,

 CREATE TABLE products (
        id     integer,
        name    varchar(40),
        PRIMARY KEY(id)
    );

//加入属性和产品

    CREATE TABLE attributes_products (
        product_id     integer,
        attibute_id integer 
    );

//属性 //例如蓝色,黄色,绿色,xl,xxl,l,s,vneck,crewneck

    CREATE TABLE attributes (
        id     integer,
        label varchar(40),
        attribute_group_id integer
    );

//例如collarshape,color,size

    CREATE TABLE attribute_group (
        id     integer,
        label varchar(40)
    );

2 个答案:

答案 0 :(得分:1)

这样的事情应该这样做。

SELECT p.id, p.name 
FROM products p
INNER JOIN attributes_products ap ON ap.product_id = p.id
INNER JOIN attributes a ON ap.attibute_id = a.id
WHERE a.id in (15,17,19,20) --list of attributes selected by user
GROUP BY p.id, p.name
HAVING COUNT(DISTINCT a.attribute_group_id) = 3

答案 1 :(得分:0)

我认为此查询将提供所需的输出

SELECT * FROM products WHERE id IN (
    SELECT product_id 
    FROM attributes_products 
    GROUP BY product_id
    HAVING (array_agg(attibute_id) @>  ARRAY[90,93])
)


SELECT * FROM products 
INNER JOIN (
    SELECT product_id 
    FROM attributes_products 
    GROUP BY product_id
    HAVING (array_agg(attibute_id) @>  ARRAY[90,93])
) AS availableproduts ON products.id = availableproduts.product_id


SELECT * FROM products 
WHERE EXISTS (
    SELECT 1 
    FROM attributes_products 
    WHERE products.id = product_id
    GROUP BY product_id
    HAVING (array_agg(attibute_id) @>  ARRAY[90,93])
)

90,93是您的属性的ID

sqlfiddle就在这里

有关阵列功能的更多详细信息,请参见
Array Functions and OperatorsAggregate Functions