【问题标题】:Mysql Dupplicate results of query relation with 2 other table , IN operatorMysql与其他2个表的查询关系重复结果,IN运算符
【发布时间】:2021-09-03 10:54:51
【问题描述】:

我有 3 个主表:productsstorescategories

  • 产品通过表 product_store

    stores 进行多对多关联
  • 产品通过表 product_category

    categories 进行多对多关联

我如何查询所有产品,属于一家商店(使用 store_id : 1)并属于一个或多个类别(使用 [4,5,6] 中的 category_id?我使用了以下语法,但结果有重复的产品记录(对于例如,第 5 类和第 6 类的产品将显示 2 次)。我可以让它独一无二吗?

select 
  "products"."name" 
from 
  "products" 
  inner join "product_categories" as "categories_join" on "categories_join"."product_id" = "products"."id" 
  inner join "categories" on "categories_join"."category_id" = "categories"."id" 
  inner join "product_stores" as "stores_join" on "stores_join"."product_id" = "products"."id" 
  inner join "stores" on "stores_join"."store_id" = "stores"."id" 
where 
  "categories"."id" in ( 4,5,6,7 ) 
  and "stores"."id" = 1

【问题讨论】:

  • 只需SELECT DISTINCT
  • 谢谢,这么简单

标签: mysql sql


【解决方案1】:

您可以使用select distinct 仅退回一件产品。但是,您也可以通过删除 join 来简化查询。不需要 storescategories 表,因为您只使用 id 并且这些在联结表中可用。我也会使用更简单的表别名:

select distinct p."name" 
from "products" p join
     "product_categories" pc
     on pc."product_id" = p."id" join
     "product_stores" ps
     on ps."product_id" = p."id" 
where pc.category_id in ( 4,5,6,7 ) and
      ps."id" = 1;

注意:您应该避免使用双引号作为标识符。如果您的表是使用它们定义的,那么我建议修复表定义。

反过来,使用exists 这个查询可能会更有效,因为不再需要select distinct

select p."name" 
from "products" p
where exists (select 1
              from "product_categories" pc
              where pc."product_id" = p."id" andf
                    pc.category_id in ( 4,5,6,7 ) 
             ) and
      exists (select 1
              from "product_stores" ps
              where ps."product_id" = p."id" and
                    ps."id" = 1
             );

【讨论】:

  • oop,我太依赖 ORM,忘了原始查询。它真的很有帮助
猜你喜欢
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
  • 1970-01-01
  • 2019-03-21
  • 2017-05-24
相关资源
最近更新 更多