Skip to content
Advertisement

Mysql duplicate results of query relation with 2 other table , IN operator

I have 3 main table : products, stores and categories

  • product relate many-to-many with stores via table product_store

  • product relate many-to-many with categories via table product_category

How can i query all products, belongs a store ( with store_id : 1 ) and belongs one or many category ( with category_id in [ 4,5,6 ] ? I used below syntax, but result has duplicated product records (for example, product in both category 5 and 6, will show 2 times). Can I get it unique ?

Advertisement

Answer

You can use select distinct to return only one product. However, you can also simplify your query by removing a join. The stores and categories tables are not needed, because you are only using the ids and these are available in the junction tables. I would also use simpler table aliases:

Note: You should avoid using double quotes for identifiers. If your tables are defined using them, then I would suggest fixing the table definitions.

This query, in turn, would probably be more efficient using exists because select distinct would no longer be necessary:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement