简体   繁体   中英

MySQL query for shopping cart filter

I am using the below table for shopping cart

id  product_id  attribute_id    value
----------------------------------------
1       1           1           A,B,C
2       2           1           B,C
3       3           1           C
4       1           2           200
5       2           2           150
6       3           2           300
7       1           3           RED
8       2           3           BLUE
9       3           3           RED,GREEN
10      1           4           YES
11      2           4           NO
12      3           4           NO

I am able to form a search result from this table. There is a provision to filter the search result by attributes.

Attributes can hold the following types of values:

  1. Numeric (250)
  2. String (YES/NO)
  3. String List (A,B,C)

I need a query to get list of product_id for the below conditions

  • attribute_id = 1 and value = B or C
  • and
  • attribute_id = 2 and value = 150
  • and
  • attribute_id = 4 and value = NO

I referred a stock question ( MySQL Multiple Where Clause ) and tried but not able to get the actual output.

Use OR in your WHERE clause and also use brackets to split each condition.

SELECT id, product_id, attribute_id, value
FROM shoppingcart
WHERE (attribute_id = 1 AND value IN ('B', 'C'))
OR (attribute_id = 2 AND value = 150)
OR (attribute_id = 4 AND value = 'NO')

Try this:

SELECT product_id FROM table_name WHERE 

(attribute_id = 1 AND (
            (value LIKE 'B,%' OR value LIKE '%,B' OR value LIKE '%,B,%' OR value LIKE 'B')
            OR
            (value LIKE 'C,%' OR value LIKE '%,C' OR value LIKE '%,C,%' OR value LIKE 'C')
              )
) 

OR

(attribute_id = 2 AND value = '150')
OR

(attribute_id = 3 AND value = 'NO')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM