Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql Complex Where Clause

I really surprised when I tried below code in MySQL:

SELECT * FROM table 
  WHERE (key='free_shipping' and value='yes') 
  AND (key='price' and value='5')

It doesn't work. I need to get product that is both free_shipping is 'yes' AND price equal '5' at the same time. How can I create this query properly?

Table Structure:

contents: (TABLE 1)

CONTENT_ID   TITLE  DESCRIPTION  DATE

content_fields: (TABLE 2)

FIELD_ID   CONTENT_ID    KEY_NAME    VALUE

Example (Get product that has 1 ID and its shipping is FREE):

SELECT *  FROM `contents` as c LEFT JOIN `content_fields` as cf ON  c.content_id = cf.content_id WHERE c.content_id = 1 AND  cf.key_name = 'free_shipping' AND cf.value = 'yes'
like image 369
kuzey beytar Avatar asked Dec 14 '25 18:12

kuzey beytar


2 Answers

Your current query is contradictory as a single row can never match the WHERE clause. I assume you want something like this.

SELECT product_id
FROM table 
WHERE (key='free_shipping' and value='yes') or (key='price' and value='5')
GROUP BY product_id
HAVING COUNT(DISTINCT key) = 2
like image 51
Martin Smith Avatar answered Dec 17 '25 18:12

Martin Smith


Try this:

WHERE free_shipping='yes' AND price='5'

or:

WHERE free_shipping=yes AND price=5

if the fields aren't strings

like image 32
Andrew Cooper Avatar answered Dec 17 '25 17:12

Andrew Cooper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!