Skip to content
Advertisement

Finding all products with same keywords

I’ve got three tables:

If I want to return all products with the same keywords as a given product, how would I do this?

I’ve tried something along the lines of:

Can’t figure it out.

Advertisement

Answer

One method is to concatenate the keywords together and use that string for joining:

Another method is more cumbersome but uses more traditional SQL. Do a self-join on keywords and a lot of counting:

The left join keeps all keywords for each product. The having then does two things:

  • The count(*) = count(p1.keyword) returns only rows where all keywords match.
  • The count(*) = <subquery> ensures that the number of keywords is the number for the first product.

Both of these formulations assume no duplicates in product_keywords, which seems like a reasonable assumption. Judicious use of distinct works if that is an issue.

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