复杂SQL查询条件中的语法错误

时间:2014-09-04 02:35:13

标签: mysql join left-join

我的sql语句遇到了一些问题。

以下是相关表格的图片:

enter image description here

产品可以分为多个类别。 单个产品可以有多种多样的类别(即:尺寸,颜色等) 多种类别可以有多种多样的选择(即:小,中,大)

表searchcriteria.criterianame松散地涉及varietycategory.category

表searchcriteriaoption.criteriaoption松散地涉及varietycategoryoption.descriptor。

我得到searchcriteria.criterianame并使用该字符串作为我们想要与varietycategory.category匹配的值,我们还必须获取各种searchcriteriaoption.criteriaoption字符串(对于该searchcriteria.criterianame)并将其与varietycategoryoption.descriptor相匹配对于该varietycategory.category。

这是sql:

    SELECT DISTINCT categories.*, product.*
FROM (categories, product, product_category) 
LEFT JOIN varietycategory ON varietycategory.productid = product.id
LEFT JOIN varietycategoryoption ON varietycategoryoption.varietycategoryid = varietycategory.id
WHERE product_category.categoryid=4 
AND product.id=product_category.productid 
AND categories.category_id=product_category.categoryid 
AND (
      (varietycategory.category = 'color' AND (varietycategoryoption.descriptor='red' OR varietycategoryoption.descriptor='blue'))
      OR 
      (varietycategory.category = 'size' AND (varietycategoryoption.descriptor = 'small' OR varietycategoryoption.descriptor='medium'))
    )

但是我收到了错误:

  

未知栏' varietycategory.id'在' on条款'

我试图找出我做错了什么。我尝试简化查询(只是为了尝试确定sql查询的哪个部分导致问题)只匹配searchcriteria.category字符串和varietycategory.category,并且查询正确地返回数据集。 以下是工作查询(此查询已简化且不足)

SELECT DISTINCT categories.*, product.*

FROM (categories, product, product_category) 
LEFT JOIN varietycategory ON varietycategory.productid = product.id
WHERE product_category.categoryid=4 
AND product.id=product_category.productid 
AND categories.category_id=product_category.categoryid 
AND (varietycategory.category = 'color' OR varietycategory.category = 'size' OR varietycategory.category='shape');

但我也需要能够与各种类别的选项相匹配。

为了避免混淆,我只使用searchcriteria来获取字段类别,并将其用作字符串以匹配varietycategory.category 我只使用searchcriteriaoption获取字段criteriaoption并将其用作字符串以匹配varietycategoryoption.descriptor

有人知道我的第一次查询错误吗? 请提供帮助,因为SQL不是专业知识。

谢谢!

3 个答案:

答案 0 :(得分:2)

错误发生在:

  OR 
  (varietycategory.category = 'size' (varietycategoryoption.desciptor = 'small' OR varietycategoryoption.descriptor='medium'))
                                    ^
                                    |
An operator (AND, OR) is missing here

顺便说一句,这与连接语法无关。

答案 1 :(得分:1)

不要混合隐式和显式连接。您的查询应如下所示:

SELECT DISTINCT c.*, p.*
FROM product_category pc join
     categories c
     on c.category_id = pc.categoryid join
     product p
     on p.id = pc.productid join
     varietycategory vc
     ON vc.productid = p.id
WHERE c.categoryid = 4 AND
      vc.category in ('color', 'size', 'shape');

您可能不需要distinct,但这取决于数据。 left join是不必要的,因为您要对where中的第二个表进行过滤。

一个简单的规则:永远不要在from子句中使用逗号。为了提供帮助,MySQL提供了一些范围规则,当您混合使用隐式和显式连接语法时,这些规则可能导致查询中断。

答案 2 :(得分:0)

问题是桌子上的一个拼写错误的字段,我将其命名为 vcid,当我几乎总是将我的表主键ID命名为" id"。