开发者

Chaining queries - Can't get AND/OR working

开发者 https://www.devze.com 2023-01-31 15:01 出处:网络
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:

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 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号