即使使用group by也返回重复行

2exbekwf  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(614)

这是我的问题

SELECT p.book FROM customers_books p 
INNER JOIN books b ON p.book = b.id 
INNER JOIN bookprices bp ON bp.book = p.book 
WHERE b.status = 'PUBLISHED' AND bp.currency_code = 'GBP' 
AND p.book NOT IN (SELECT cb.book FROM customers_books cb WHERE cb.customer = 1) 
GROUP BY p.book, p.created_date ORDER BY p.created_date DESC

这是我的客户帐簿表中的数据,

我期望只有8,6,1的books id返回,但是query返回8,6,1,1
表结构在这里

CREATE TABLE "public"."customers_books" (
  "id" int8 NOT NULL,
  "created_date" timestamp(6),
  "book" int8,
  "customer" int8,
);

CREATE TABLE "public"."books" (
  "id" int8 NOT NULL,
  "created_date" timestamp(6),
  "status" varchar(255) COLLATE "pg_catalog"."default",
)

CREATE TABLE "public"."bookprices" (
  "id" int8 NOT NULL,
  "currency_code" varchar(255) COLLATE "pg_catalog"."default",
  "book" int8
)

你觉得我做错什么了。我真的不想用 p.created_dategroup by 但我被迫使用,因为 order by

uubf1zoe

uubf1zoe1#

外部查询中的联接太多:

SELECT b.book
FROM books b INNER JOIN
     bookprices bp
     ON bp.book = p.book 
WHERE b.status = 'PUBLISHED' AND bp.currency_code = 'GBP' AND
      NOT EXISTS (SELECT 1
                  FROM customers_books cb
                  WHERE cb.book = p.book AND cb.customer = 1
                 ) ;

注意,我替换了 NOT INNOT EXISTS . 我强烈地,强烈地劝阻你不要使用 NOT IN 使用子查询。如果子查询返回 NULL 价值观,那么 NOT IN 完全不返回任何行。最好只是通过使用 NOT EXISTS .

相关问题