我有多个包含样本数据的表格:
CREATE TABLE public.languages (
"id" bigserial NOT NULL,
PRIMARY KEY ("id")
);
CREATE TABLE public.goods (
"id" bigserial NOT NULL,
PRIMARY KEY ("id")
);
CREATE TABLE public.good_texts (
goodid int8 NOT NULL,
title varchar(250) NOT NULL,
languageid int8 NOT NULL,
PRIMARY KEY (goodid, languageid)
);
CREATE TABLE "public".filtervariants (
id bigserial NOT NULL,
PRIMARY KEY (id));
CREATE TABLE "public".filtervariant_good (
filtervariantid int8 NOT NULL,
goodid int8 NOT NULL,
PRIMARY KEY (goodid,
filtervariantid));
INSERT INTO "public"."languages" VALUES ('1');
INSERT INTO "public"."goods" VALUES ('385');
INSERT INTO "public"."good_texts" VALUES ('385', 'Dell Inspiron 5559', '1');
INSERT INTO "public"."filtervariants" VALUES ('1');
INSERT INTO "public"."filtervariants" VALUES ('2');
INSERT INTO "public"."filtervariants" VALUES ('3');
INSERT INTO "public"."filtervariants" VALUES ('4');
INSERT INTO "public"."filtervariant_good" VALUES ('1', '385');
INSERT INTO "public"."filtervariant_good" VALUES ('3', '385');
此查询
SELECT
gt.*, goods.*
FROM
good_texts gt
JOIN goods ON goods. ID = gt.goodid
JOIN filtervariant_good ON goods.id = filtervariant_good.goodid
WHERE
gt.languageid = 1
两次返回记录,我无法理解原因。每当我删除
JOIN filtervariant_good ON goods.id = filtervariant_good.goodid
行只返回一次记录
请解释此次加入有什么问题。如果我将此表与其他表(此处未显示)结合使用,则可以正常工作。
答案 0 :(得分:1)
嗯,filtervariant_good中有两行,goodid
等于385,这就是原因。我怀疑你不关心在该表中有多行,而你只关心该表中是否存在商品。如果我的猜测是正确的,那么您可以执行以下操作:
SELECT
gt.*, goods.*
FROM
good_texts gt
JOIN goods ON goods. ID = gt.goodid
WHERE
gt.languageid = 1
AND exists(SELECT FROM filtervariant_good WHERE goods.id = filtervariant_good.goodid)
这将仅返回filtervariant_good
中存在的商品。