0

我的查询有误

这是我的查询

SELECT a.id_stock, a.color, a.size, (SUM(IFNULL(a.barang_masuk,0)) - SUM(IFNULL(a.reject,0)) - IFNULL((
    SELECT SUM(IFNULL(qty,0)) AS SUMqty FROM transaksi WHERE transaksi.id_stock = a.id_stock GROUP BY id_stock
),0)) AS sold FROM stock a
WHERE a.no_barang='10' AND sold>0
GROUP BY a.no_barang, a.color, a.size
ORDER BY color, size ASC

这是错误

#1054 - Unknown column 'sold' in 'where clause'

有什么建议解决这个问题吗?谢谢

4

1 回答 1

1

HAVING您需要为此使用的 where 子句不处理自定义别名

SELECT a.id_stock, a.color, a.size, (SUM(IFNULL(a.barang_masuk,0)) - SUM(IFNULL(a.reject,0)) - IFNULL((
    SELECT SUM(IFNULL(qty,0)) AS SUMqty FROM transaksi WHERE transaksi.id_stock = a.id_stock GROUP BY id_stock
),0)) AS sold FROM stock a
HAVING a.no_barang='10' AND sold>0
GROUP BY a.no_barang, a.color, a.size
ORDER BY color, size ASC

对于这个问题,我猜你不能使用 before group by 你可以使用 subselect

SELECT q.* FROM (
    SELECT a.id_stock, a.color, a.size, (SUM(IFNULL(a.barang_masuk,0)) - SUM(IFNULL(a.reject,0)) - IFNULL((
        SELECT SUM(IFNULL(qty,0)) AS SUMqty FROM transaksi WHERE transaksi.id_stock = a.id_stock GROUP BY id_stock
    ),0)) AS sold FROM stock a

    HAVING a.no_barang='10' AND sold>0 
 /* you can use where and having both in same query like WHERE a.no_barang='10' HAVING sold>0 */

    ORDER BY color, size ASC ) q  GROUP BY q.no_barang, q.color, q.size

编辑

SELECT a.id_stock, a.color, a.size, (SUM(IFNULL(a.barang_masuk,0)) - SUM(IFNULL(a.reject,0)) - IFNULL((
    SELECT SUM(IFNULL(qty,0)) AS SUMqty FROM transaksi WHERE transaksi.id_stock = a.id_stock GROUP BY id_stock
),0)) AS sold FROM stock a
WHERE a.no_barang='10' 
GROUP BY a.no_barang, a.color, a.size
HAVING sold>0
ORDER BY color, size ASC

Where 子句中的未知列

Mysql的Having子句后如何使用GROUP BY

于 2013-11-15T10:33:39.927 回答