1

这让我很困惑,在阅读了许多论坛和“如何”网站之后,我想我更困惑为什么这不起作用。

我有 2 个要加入的表。

表 1(产品)包含我所有的产品详细信息。

表 2(评级)包含每个产品的所有评级,每个产品都有来自 3 个不同评级实体的 3 个评级。

我正在研究一组 AJAX 搜索过滤器,并且需要以包含所有过滤器的方式编写查询。

过滤器包括价格、评论数量、平均评论星级、评分 1、评分 2、评分 3。

价格、评论数量和平均星级来自表 1(产品)。

等级 1、2 和 3 来自表 2(等级)。

我的查询需要这样的东西,但是当我知道(已在数据库中验证)我有符合我正在查询的标准的记录时,这将返回零结果。

SELECT p.id, p.name 
FROM products p 
JOIN ratings r ON p.id = r.id 
WHERE p.num_reviews BETWEEN '0' AND '1000' 
AND p.price BETWEEN '0' AND '500' 
AND p.avg_rvw_stars BETWEEN '0' AND '5' 
AND (r.ratingSource='1' AND (r.rating BETWEEN '1' AND '4')) 
AND (r.ratingSource='2' AND (r.rating BETWEEN '0' AND '100')) 
AND (r.ratingSource='3' AND (r.rating BETWEEN '0' AND '100')) 
ORDER BY p.name ASC

问题似乎存在于最后三个 WHERE 语句中。如果我删除 3 个中的任何 2 个,我会得到结果。但是当我包括所有 3 个时,当有符合条件的记录时,我什么也得不到。

如果我将最后两个 AND 更改为 OR,我也会得到结果,但这不是预期或需要的结果集。

我写得不正确吗?

非常感谢任何帮助/指导!

4

3 回答 3

3

您的问题是您混淆了ANDand的含义OR

例如,您正在寻找具有

r.ratingSource='1'

稍后他们也应该有

r.ratingSource='2'

没有什么是有效的,因为它是一个单一的东西,不能两者兼而有之。所以你需要考虑做什么AND

如果你有一些每个结果必须有的东西,你应该使用 AND。如果你有他们可能有的东西组,你可以做(thing AND otherthing) OR (thing2 and otherthing2)

这都是基本逻辑:)

我想你可能是这个意思:

SELECT p.id, p.name 
FROM products p 
JOIN ratings r ON p.id = r.id 
WHERE p.num_reviews BETWEEN '0' AND '1000' 
AND p.price BETWEEN '0' AND '500' 
AND p.avg_rvw_stars BETWEEN '0' AND '5' 
AND (
        (r.ratingSource='1' AND (r.rating BETWEEN '1' AND '4')) 
     OR (r.ratingSource='2' AND (r.rating BETWEEN '0' AND '100')) 
     OR (r.ratingSource='3' AND (r.rating BETWEEN '0' AND '100'))
) 
ORDER BY p.name ASC
于 2012-08-26T12:45:01.353 回答
2

如果您有 3 个不同的评级行,则不能使用该逻辑。每行都会检查WHERE一次条件,因此不能有一个同时具有1和评级的行2

最简单的方法是三次加入:

SELECT p.id, p.name 
FROM products p 
  JOIN ratings r1 ON  p.id = r1.id 
                  AND r1.ratingSource = 1
                  AND r1.rating BETWEEN 1 AND 4
  JOIN ratings r2 ON  p.id = r2.id 
                  AND r2.ratingSource = 2
                  AND r2.rating BETWEEN 0 AND 100
  JOIN ratings r3 ON  p.id = r3.id
                  AND r3.ratingSource = 3
                  AND r3.rating BETWEEN 0 AND 100
WHERE p.num_reviews BETWEEN 0 AND 1000 
  AND p.price BETWEEN 0 AND 500 
  AND p.avg_rvw_stars BETWEEN 0 AND 5 
ORDER BY p.name ASC ;
于 2012-08-26T12:56:27.357 回答
1

我想你需要

AND 
(
     (r.ratingSource='1' AND (r.rating BETWEEN '1' AND '4')) 
      OR (r.ratingSource='2' AND (r.rating BETWEEN '0' AND '100')) 
      OR (r.ratingSource='3' AND (r.rating BETWEEN '0' AND '100')) 
    )
于 2012-08-26T12:45:29.977 回答