MySQL查询错误1054

时间:2012-05-11 18:12:03

标签: mysql sql

我有 MySQL 查询

SELECT count( * ) AS total
FROM `orders` o, `orders_status` s, `orders_status_history` osh
LEFT JOIN `orders_total` ot ON ot.orders_id = o.orders_id
WHERE o.orders_status = s.orders_status_id
AND osh.orders_id = o.orders_id
AND s.language_id = '5'
AND s.orders_status_id = '6'
AND ot.class = 'ot_total'

收到此错误:

#1054 - Unknown column 'o.orders_id' in 'on clause'

我的表架构如下:

CREATE TABLE IF NOT EXISTS `orders` (
  `orders_id` int(11) NOT NULL auto_increment,
  `customers_id` int(11) NOT NULL default '0',
  `last_modified` datetime default NULL,
  `orders_status` int(5) NOT NULL default '0',
  `orders_date_finished` datetime default NULL,
  `comments` text,
  `currency` char(3) default NULL,
  `currency_value` decimal(14,6) default NULL,
  `invoice_number` varchar(100) default NULL,
  PRIMARY KEY  (`orders_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=cp1251 AUTO_INCREMENT=8419 ;

我无法理解错误的来源。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您的订单表的表别名为OR。您需要更改表别名。

SELECT count( * ) AS total
FROM `orders` o , `orders_status` s, `orders_status_history` osh
LEFT JOIN `orders_total` ot ON ot.orders_id = or.orders_id
WHERE o.orders_status = s.orders_status_id
AND osh.orders_id = or.orders_id
AND s.language_id = '5'
AND s.orders_status_id = '6'
AND ot.class = 'ot_total'

您还应该更改JOIN语法

SELECT count( * ) AS total
FROM `orders` o 
LEFT JOIN `orders_status` s
    ON o.order_status = s.orders_status_id
LEFT JOIN `orders_status_history` osh
    ON osh.orders_id = o.orders_id  
LEFT JOIN `orders_total` ot 
    ON ot.orders_id = o.orders_id
WHERE s.language_id = '5'
    AND s.orders_status_id = '6'
    AND ot.class = 'ot_total'

答案 1 :(得分:2)

the manual中所述:

  

以前,逗号运算符(,)和JOIN都具有相同的优先级,因此连接表达式t1, t2 JOIN t3被解释为((t1, t2) JOIN t3)。现在JOIN具有更高的优先级,因此表达式被解释为(t1, (t2 JOIN t3))。此更改会影响使用ON子句的语句,因为该子句只能引用连接操作数中的列,并且优先级的更改会更改这些操作数的解释。

     

示例:

CREATE TABLE t1 (i1 INT, j1 INT);
CREATE TABLE t2 (i2 INT, j2 INT);
CREATE TABLE t3 (i3 INT, j3 INT);
INSERT INTO t1 VALUES(1,1);
INSERT INTO t2 VALUES(1,1);
INSERT INTO t3 VALUES(1,1);
SELECT * FROM t1, t2 JOIN t3 ON (t1.i1 = t3.i3);
     

以前,SELECT是合法的,因为t1,t2隐式分组为(t1,t2)。现在JOIN优先,因此ON子句的操作数为t2t3。由于t1.i1不是任一操作数中的列,因此结果为Unknown column 't1.i1' in 'on clause'错误。要允许处理连接,请使用括号将前两个表显式分组,以便ON子句的操作数为(t1,t2)t3

SELECT * FROM (t1, t2) JOIN t3 ON (t1.i1 = t3.i3);
     

或者,避免使用逗号运算符并改为使用JOIN

SELECT * FROM t1 JOIN t2 JOIN t3 ON (t1.i1 = t3.i3);
     

此更改也适用于将逗号运算符与INNER JOINCROSS JOINLEFT JOINRIGHT JOIN混合在一起的语句,所有这些语句现在都具有比逗号更高的优先级操作

答案 2 :(得分:1)

或者是一个mysql关键字!用其他东西替换它,例如_or&再试一次!