从2个表中选择,使用JOIN并通过ID连接

时间:2014-02-28 16:40:59

标签: mysql sql join

在这个主题的任何地方都很难搜索...基本上,我从两个表中选择,每个表都有JOIN个子句。如果我按每个表分开查询,两者都可以正常工作......下面看起来对我来说逻辑正确..但它给了我一个错误:

Error Code: 1054. Unknown column 'catalogue.ID' in 'on clause'  0.000 sec

这个查询是否可行,我在这里缺少什么?

SELECT  `catalogue`.`ID`,`catalogue`.`Catalogue`,`catalogue`.`Artist`,`catalogue`.`Title`, `catalogue`.`Street_Date`,
        `label`.`label_name` as `label`,
        `format`.`format_name` as `Format`,
        `schedule`.designer,`schedule`.`MO`,

        `packtype`.`description` as `Package`,
        `manufacturer`.`description` as `Manufacturer`

        FROM `catalogue`, `manufacture`

        LEFT JOIN `schedule` ON (`schedule`.`cat_id` = `catalogue`.`ID`) 
        LEFT JOIN `label` ON (`catalogue`.`label` = `label`.`Lbl_ID`) 
        LEFT JOIN `format` ON (`catalogue`.`format` = `format`.`Fmt_ID`) 

        LEFT JOIN `packtype` ON `packtype`.`pack_id` = `manufacture`.`pack_id`
        LEFT JOIN `manufacturer` ON `manufacturer`.`man_id` = `manufacture`.`manuf`

    WHERE `catalogue`.`Street_Date`="2014-03-17" and  `manufacture`.`cat_id` = `catalogue`.`ID`

    ORDER BY  `catalogue`.`Catalogue`  asc LIMIT 1 , 10

1 个答案:

答案 0 :(得分:5)

您正在混合join类型,因此这是您遇到的问题之一。您可以将,替换为cross join

来解决此问题
    FROM `catalogue` cross join `manufacture`

    LEFT JOIN `schedule` ON (`schedule`.`cat_id` = `catalogue`.`ID`) 
    LEFT JOIN `label` ON (`catalogue`.`label` = `label`.`Lbl_ID`) 
    LEFT JOIN `format` ON (`catalogue`.`format` = `format`.`Fmt_ID`) 

    LEFT JOIN `packtype` ON `packtype`.`pack_id` = `manufacture`.`pack_id`
    LEFT JOIN `manufacturer` ON `manufacturer`.`man_id` = `manufacture`.`manuf`

然而,令我惊讶的是这些表之间没有join条件。

哦,我在where看到了这个状况。呸!

    FROM `catalogue`
    LEFT JOIN `manufacture` ON `manufacture`.`cat_id` = `catalogue`.`ID`

    LEFT JOIN `schedule` ON (`schedule`.`cat_id` = `catalogue`.`ID`) 
    LEFT JOIN `label` ON (`catalogue`.`label` = `label`.`Lbl_ID`) 
    LEFT JOIN `format` ON (`catalogue`.`format` = `format`.`Fmt_ID`) 

    LEFT JOIN `packtype` ON `packtype`.`pack_id` = `manufacture`.`pack_id`
    LEFT JOIN `manufacturer` ON `manufacturer`.`man_id` = `manufacture`.`manuf`

这个问题实际上是documented

  

但是,逗号运算符的优先级小于INNER   JOIN,CROSS JOIN,LEFT JOIN等等。如果你混合使用逗号连接   当有连接条件时,其他连接类型,错误   form可能会出现'on子句'中的未知列'col_name'。信息   关于这个问题的处理将在本节后面给出。

简单的解决方案是:永远不要在,子句中使用from。如果您想要交叉联接,请使用cross join