mySQL - sql查询多连接问题

时间:2015-01-25 18:03:51

标签: mysql

我的头衔可能不是最具说明性的。

所以我会进一步解释我的问题。

我有四张桌子:

Category
- idCategory varchar(100) COLLATE utf8_bin NOT NULL
- idMerchant int(11) NOT NULL
- parentCategory varchar(100) CHARACTER SET utf8 DEFAULT NULL
- level int(11) NOT NULL <-- here the data represent the level of the category
- label varchar(100) CHARACTER SET utf8 NOT NULL
- PRIMARY KEY (`idCategory`,`idMerchant`),

Product
- idProduct int(11) NOT NULL AUTO_INCREMENT
- idCategory varchar(100) NOT NULL
- description varchar(100) DEFAULT NULL
- label varchar(100) DEFAULT NULL
- PRIMARY KEY (`idProduct`)


ProductAttribute
- idProduct int(11) NOT NULL
- idAttribute int(11) NOT NULL
- PRIMARY KEY (`idProduct`,`idAttribute`)

Attribute
- idAttribute int(11) NOT NULL
- code varchar(100) DEFAULT NULL
- label varchar(100) DEFAULT NULL
- PRIMARY KEY (`idAttribute`)

我的目标是通过类别及其子类别获取数据。每个子类别都有自己的产品,最后每个子类别都有多个属性。

SELECT pc.label, pc.level, c.label as 'C_label', c.level, p.label as 'P_label', a.label as 'A_Label' 
FROM `Category` c join `Product` p using(idCategory) 
JOIN `ProductAttribute` using(idProduct) 
JOIN `Attribute` a using(idAttribute) 
JOIN (
      Select idCategory, label 
      FROM Category Where level = 1 and idMerchant = 65
) as pc 
ON c.parentCategory=pc.idCategory WHERE idMerchant = 65

我的期望是找到这样的桌子:

label | level | C_label | level | P_label | A_Label
Boy   |     1 | Watch   |     2 |  Brand  | Festina   
...   |     1 | Watch   |     2 |  Brand  |Pequignet
...   |   ... |   ...   |   ... |    ...  |     ...
Girl  |     1 | Watch   |     2 |  Brand  |Bell & Ross
...

等...

但结果是这样的:

label | level | C_label | level | P_label | A_Label
Boy   |     1 | Watch   |     2 |   Size  |Bell & Ross
...   |     1 | Watch   |     2 |   Size  |   Burton
...   |   ... |   ...   |   ... |    ...  |Coca-Cola <-- I have some brand which are not related with the category
Girl  |     1 | Watch   |     2 |   Size  |  Swiffer <-- Other example
...

对于此示例,许多品牌按字母顺序列出,但与相关产品无关。但有时候对于某些属性,产品的属性是显而易见的,比如仅列出分辨率的电视。

那么你能告诉我为什么查询不正确。

感谢。

1 个答案:

答案 0 :(得分:0)

我不知道此查询如何无法返回错误,因为除了此谓词外,我没有看到对行源 h 的任何引用:

ON h.parentCode=pc.idCategory 
   ^

我也没有在您列出列名的四个表中看到任何名为 parentCode 的列。我没有看到列的数据类型(任何隐式数据转换?),任何键定义(主键,唯一键,外键)。没有足够的信息来进一步诊断查询问题。

有时,&#34;错误的结果&#34;您报告的类型是表中值的问题。为了诊断这一点,我们修改查询以包括SELECT列表中JOIN谓词中使用的所有PRIMARY KEY列和列。

相关问题