【发布时间】:2009-07-11 22:06:09
【问题描述】:
我有这样的 m2m 关系:
#main table
CREATE TABLE products_product (
id integer NOT NULL,
company_id integer,
user_id integer,
type_id integer NOT NULL,
name character varying(100) NOT NULL,
description character varying(200) NOT NULL,
tags character varying(255) NOT NULL,
image character varying(200) NOT NULL
);
#intermediate table
CREATE TABLE products_ingridientbound (
id integer NOT NULL,
ingridient_id integer NOT NULL,
company_id integer NOT NULL,
price double precision NOT NULL,
active boolean NOT NULL,
"asTopping" boolean NOT NULL
);
#final m2m table
CREATE TABLE products_ingridientproductbound (
id integer NOT NULL,
product_id integer NOT NULL,
ingridient_id integer NOT NULL,
"optionValue" integer NOT NULL,
CONSTRAINT "products_ingridientproductbound_optionValue_check" CHECK (("optionValue" >= 0))
);
我想要做的就是得到产品,它有 2 个(在这个例子中)ingridient 组,一个 ID 在范围 (16, 17, 18, 19) 中,另一个在范围 (43, 44, 45) .我希望 ingridient ID 同时在两个组中。
我的查询看起来像这样(它实际上是由 django orm 生成的):
SELECT "products_product"."id","products_product"."name",
FROM "products_product"
INNER JOIN "products_ingridientproductbound"
ON ("products_product"."id" = "products_ingridientproductbound"."product_id")
WHERE ("products_ingridientproductbound"."ingridient_id" IN (16, 17, 18, 19)
AND "products_ingridientproductbound"."ingridient_id" IN (43, 44, 45)) LIMIT 21
它给了我 0 个结果,但如果我只使用一组 IN 查询运行查询,它就会起作用!
这是我的“products_ingridientproductbound”表中的数据。我认为我的查询可以返回产品 3,因为它在两个组(16 和 45)中都是如此,但现在我有点困惑。 Screenshot of phpPgAdmin
【问题讨论】:
-
从谷歌上的快速搜索来看,postgres 确实支持 intersect 运算符。看我的回答。
-
您可以为开发人员做的最好的事情是在您离开时维护它(并使您在老板看来更专业) - 在数据库中正确拼写“成分”。这是一件小事,但它真的很重要。
标签: sql postgresql many-to-many