Chaining queries - Can't get AND/OR working
After analyzing my issue, I think I may need to use the "union" operator in SQL, however I'm unsure. Anywho I'm chaining my queries in codeigniter to come out with this query:
SELECT *
FROM (`deals`)
WHERE `category` = 'books'
AND `host` = 'amazon'
OR `host` = 'zappos'
OR `host` = 'newegg'
ORDER BY `time` desc
So it selects things that aren't in the category books, but are from those hosts. So I'm looking to make it so it returns only results in books, AND have a host of any o开发者_如何学Gof those three. I would prefer doing this with a database query rather than manually filtering afterwards. I am using MySQL with an innoDB table. Thanks
Use brackets to make it work as desired.
SELECT *
FROM (`deals`)
WHERE `category` = 'books'
AND ( `host` = 'amazon'
OR `host` = 'zappos'
OR `host` = 'newegg' )
ORDER BY `time` desc
Or use the 'IN' keyword:
SELECT *
FROM (`deals`)
WHERE `category` = 'books'
AND `host` IN ( 'amazon', 'zappos', 'newegg' )
ORDER BY `time` desc
Try some parentheses:
SELECT *
FROM (`deals`)
WHERE `category` = 'books'
AND (
`host` = 'amazon'
OR `host` = 'zappos'
OR `host` = 'newegg'
)
ORDER BY `time` desc
精彩评论