Search code examples
mysqlsqlinnodb

Selecting multiple products from the same category?


Statement Attempt 1:

It seemed to ignore everything and get products from anywhere regardless of country

SELECT *
FROM products
WHERE `country` = 'America' AND
      product = 'Product 1' AND
      product = 'Product 2' AND
      completed = 'complete'

Statement Attempt 2:

The result of this was that is returned 0 results, even though the results are there hypothetically.

SELECT *
FROM products
WHERE `country` = 'America' AND
      product = 'Product 1' OR
      product = 'Product 2' AND
      completed = 'complete'

Solution

  • Your first query is logically incorrect due to product = product 1 AND product = product 2, where clause filter rows one by one, so a single row at same time cannot contain both values in product column.


    Your second query has an issue that you introduced and OR criteria so it ignores the country filter if there is product 2 with status completed in another country , to correct your query you need to group your OR criteria by using parenthesis (condition 1 or condition 2) and some other condition

    SELECT *
    FROM products
    WHERE `country` = 'America'
          AND (product = 'Product 1' OR product = 'Product 2')
          AND completed = 'complete'
    

    Or you could use IN clause to simplify your criteria

    SELECT *
    FROM products
    WHERE `country` = 'America'
          AND product IN('Product 1','Product 2')
          AND completed = 'complete'