MySQL:子查询未知列

时间:2019-03-15 14:40:45

标签: mysql

我的查询遇到了问题。我有一个包含订单,订单交易,订单产品和订单运输成本的数据库。现在,我要所有客户未完全支付订单的订单。

我创建了一个数据库提琴here

通过此查询,我可以获取特定订单的订单总数,在这种情况下为订单1:

SELECT SUM(total) AS orderTotal
FROM (
    SELECT order_id, SUM(price * amount) AS total
    FROM order_product
    WHERE order_id = '1'

    UNION ALL           
    SELECT order_id, price AS total
    FROM order_shipping
    WHERE order_id = '1'
) subtable
WHERE order_id <> 0 GROUP BY order_id

现在,我希望所有支付金额(order_transaction)小于订单总额的订单。我尝试了以下查询,但它告诉我: Unknown column 'o.id' in 'where clause'。没有行号,但在下面的查询中的行12上。

SELECT SQL_CALC_FOUND_ROWS o.id
FROM `order` o
WHERE (
        SELECT IFNULL(SUM(price),0) AS transactionTotal
        FROM order_transaction 
        WHERE order_id = o.id
      ) <=
      (
        SELECT SUM(total) AS orderTotal
        FROM (
            SELECT order_id, SUM(price * amount) AS total
            FROM order_product
            WHERE order_id = o.id

            UNION ALL           
            SELECT order_id, price AS total
            FROM order_shipping
            WHERE order_id = o.id
        ) subtable
        WHERE order_id <> 0 GROUP BY order_id
      ) 
ORDER BY o.id DESC
LIMIT 0, 10;

我不明白,这不适用于第二个子查询,而它在第一个子查询(在order_transaction表上)中却能正常工作。

预期结果:

o.id 
------
 1
 2
 4
 8
 9
10

在我的数据库模式下面

CREATE TABLE `order` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `order_product` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `amount` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `order_shipping` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `order_transaction` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:0)

FROM子句中的子查询(您的UNION查询)称为派生表

MySQL documentation about Derived Tables中,您会发现:

  

派生表不能是相关子查询。

这意味着您不能引用不在该子查询范围内的表(别名),如下所示:

WHERE order_id = o.id

但是您可以在SELECT或WHERE子句中编写相关的子查询。您的查询可以重写为:

SELECT SQL_CALC_FOUND_ROWS o.id
    , (
        SELECT IFNULL(SUM(price),0) AS transactionTotal
        FROM order_transaction 
        WHERE order_id = o.id
    ) a
    , (
        SELECT SUM(price * amount) AS total
        FROM order_product
        WHERE order_id = o.id
    ) b
    , (
        SELECT SUM(price) AS total
        FROM order_shipping
        WHERE order_id = o.id
    ) c
FROM `order` o
ORDER BY o.id DESC
LIMIT 0, 10;

HAVING a <= COALESCE(b, 0) + COALESCE(c, 0)

Demo

它不会返回您的预期结果。要解决此问题,您可能需要将<=更改为<