3

我有一张桌子可以帮助选择产品。

我想查询我在哪里找回了每条记录:

category_id = 'M10' and band_id = '010'
OR
category_id = 'M10' and band_id = '020'

AND

category_id = 'M50' and band_id = '010'
OR
category_id = 'M50' and band_id = '020'

我的查询:

SELECT 
product.entry_id AS entry_id, 
helpme.item_id AS product_id 
FROM inbound_help_me_choose helpme 
LEFT JOIN exp_channel_titles product ON (product.product_id = helpme.item_id) 
WHERE 
helpme.submarket_id = 'NZ' 
AND 
(
(helpme.category_id = 'M10' AND helpme.band_id = '010') 
OR 
(helpme.category_id = 'M10' AND helpme.band_id = '020')
)

在第一类上工作正常,但是一旦我添加新的 WHERE 条件失败:

SELECT 
product.entry_id AS entry_id, 
helpme.item_id AS product_id 
FROM inbound_help_me_choose helpme 
LEFT JOIN exp_channel_titles product ON (product.product_id = helpme.item_id) 
WHERE 
helpme.submarket_id = 'NZ' 
AND 
(
(helpme.category_id = 'M10' AND helpme.band_id = '010') 
OR 
(helpme.category_id = 'M10' AND helpme.band_id = '020')
)
AND
(
(helpme.category_id = 'M50' AND helpme.band_id = '010')
OR 
(helpme.category_id = 'M50' AND helpme.band_id = '020')
OR 
(helpme.category_id = 'M50' AND helpme.band_id = '030')
)

对我来说似乎没问题,所以我完全失去了为什么它不起作用。

4

4 回答 4

3

我想你需要这个

SELECT 
product.entry_id AS entry_id, 
helpme.item_id AS product_id 
FROM inbound_help_me_choose helpme 
LEFT JOIN exp_channel_titles product ON (product.product_id = helpme.item_id) 
WHERE 
helpme.submarket_id = 'NZ' 
AND 
(
   (helpme.category_id = 'M10' AND helpme.band_id IN ('010','020')) OR 
   (helpme.category_id = 'M50' AND helpme.band_id IN ('010','020','030'))
)
于 2013-01-13T03:07:42.253 回答
1

稍微改变一下你需要的东西:

category_id = 'M10' and band_id = '010' OR category_id = 'M10' and band_id = '020'
AND
category_id = 'M50' and band_id = '010' OR category_id = 'M50' and band_id = '020'

是相同的:

category_id = 'M10' and (band_id = '010' OR band_id = '020')
AND
category_id = 'M50' and (band_id = '010' OR band_id = '020')

是相同的:

category_id = 'M10' and category_id = 'M50'
AND
(band_id = '010' OR band_id = '020') and (band_id = '010' OR band_id = '020')

category_id不能两者兼而有之M10M50所以你不会得到任何结果......

于 2013-01-13T03:12:04.693 回答
1

您在问题中显示的第二个示例查询中的 where 子句中的条件,即在其 where 子句中遇到问题的条件,永远无法评估为真......

第一个示例中的第一个 where 子句要求 category_id 等于 M10。

然后在第二个示例中,where 子句使用“and”添加了另一组语句。问题是这个 where 子句只需要 category_id 为 M50 的记录

无论逻辑上的任何其他问题如何,我都可以相当确定您不会找到同时具有 M10 和 M50 的 category_id 的记录。

另一个用户,@rs。发布了一个带有修改的 where 子句的查询,该子句符合在开始或您的问题中指定的条件逻辑规则。

于 2013-01-13T03:18:40.717 回答
0

x AND y运算符意味着它适用的和x条件y都需要同时满足。您只需要改用OR运算符。

于 2013-01-13T03:08:44.707 回答