2

我有这个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 ;

而且我不明白错误来自哪里。有任何想法吗?

4

3 回答 3

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'
于 2012-05-11T18:14:22.990 回答
2

手册所述:

以前,逗号运算符 ( ,) 和JOIN两者具有相同的优先级,因此连接表达式t1, t2 JOIN t3被解释为((t1, t2) JOIN t3)。NowJOIN具有更高的优先级,因此表达式被解释为(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由于 as 的隐式分组, 是合法t1,t2(t1,t2)。现在JOIN优先,所以ON子句的操作数是t2and t3。因为t1.i1不是任何一个操作数中的列,所以结果是Unknown column 't1.i1' in 'on clause'错误的。要允许处理连接,请将前两个表用括号显式分组,以便ON子句的操作数是(t1,t2)and 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 JOIN, CROSS JOIN,LEFT JOIN和混合的语句RIGHT JOIN,所有这些语句现在都比逗号运算符具有更高的优先级。

于 2012-05-11T18:32:23.187 回答
1

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

于 2012-05-11T18:18:12.740 回答