Suppose that I have a table with the columns product_id and category_id , which sets the product to category. a product may have several categories.

let i have an array of id -shnykh categories, for example, such - [1,2,3] . the question is - how can I use the sql query to display the product_id only those products that belong to all three categories?

those. for example, if there are three lines 1-1 1-2 1-3 for a product with product_id in the table, then we derive it.

  • SELECT * FROM table1 where product_id in (1,2,3) ? - HELO WORD
  • @HELOWORD, no, your request will return products that have at least one category. And you need everything. - pegoopik
  • one
    About the same question was answered here.stackoverflow.com/questions/553724/… - Firepro

1 answer 1

 SELECT product_id FROM YourTable U WHERE category_id IN (1, 2, 3) GROUP BY product_id HAVING COUNT(*) = 3 
  • Thanks, that seems to be the right thing. and why where the condition generally works? we are grouping, and there may be several records. I even tried WHERE category_id = 1 (not IN), and this also returns the result - sam3434
  • There the IN operator (1, 2, 3) is equivalent to q = 1 OR q = 2 OR q = 3 - pegoopik