M
M
MasterCopipaster2022-04-08 12:12:51
MySQL
MasterCopipaster, 2022-04-08 12:12:51

How to replace where exists with join in my case?

Good day, I ran into a problem, there is a SQL query that works for quite a long time

select
  *
from
  `brands`
where
  exists (
  select
    *
  from
    `products`
  where
    `brands`.`id` = `products`.`brand_id`
    and `show` = 1
    and exists (
    select
      *
    from
      `categories`
    where
      `products`.`category_id` = `categories`.`id`
      and (`id` = 9
        or `parent_id` = 9)))


I know that people somehow rewrite them to join so that it would work faster based on a similar case

Tried to rewrite it like this:

SELECT
  *
from
  brands
inner join products ON
  `brands`.id = `products`.brand_id
left join categories ON
  `products`.`category_id` = `categories`.`id`
where
  products.`show` = 1 and (categories.id = 9 or categories.parent_id = 9);


But the data comes more than necessary

. In the first case, it will return 6 records, and in the second, 16.

Actually, there are ideas how to correct the request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MasterCopipaster, 2022-04-08
@MasterCopipaster

All by myself doper

SELECT
  DISTINCT `brands`.*
from
  brands
inner join products ON
  `brands`.id = `products`.brand_id
left join categories ON
  `products`.`category_id` = `categories`.`id`
where
  products.`show` = 1 and (categories.id = 9 or categories.parent_id = 9);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question