我得到的确切错误是:“where子句中的未知列'trans_paid'”
我的查询($ from_date和$ to_date格式正确):
SELECT
o.order_id,
o.order_po_no,
o.order_ship_date,
acct.acct_company,
SUM( ROUND( i.item_qty * i.item_price, 2 ) ) AS item_amount, (
SELECT SUM( trans_amount )
FROM transactions
WHERE order_id = o.order_id
AND trans_pending =0
AND trans_date >= '$from_date'
AND trans_date <= '$to_date'
) AS trans_paid
FROM orders AS o
INNER JOIN accounts AS acct ON o.acct_id = acct.acct_id
INNER JOIN items AS i ON o.order_id = i.order_id
WHERE (o.order_status =7 or o.order_status = 4)
AND trans_paid IS NOT NULL
AND acct.is_wholesale =1
AND acct.acct_company LIKE '%".$_POST['company']."%'
GROUP BY o.order_id
答案 0 :(得分:4)
您无法从WHERE子句中引用SELECT原因中的别名列。如果要对其进行过滤,则必须将其包装在子查询中。
答案 1 :(得分:3)
标准SQL不允许您引用WHERE
子句中的聚合列。您需要将trans_paid
条件移动到HAVING
子句才能使其正常工作。
更改
WHERE (o.order_status =7 or o.order_status = 4)
AND trans_paid IS NOT NULL
AND acct.is_wholesale =1
AND acct.acct_company LIKE '%".$_POST['company']."%'
GROUP BY o.order_id
到
WHERE (o.order_status =7 or o.order_status = 4)
AND acct.is_wholesale =1
AND acct.acct_company LIKE '%".$_POST['company']."%'
GROUP BY o.order_id
HAVING trans_paid IS NOT NULL
答案 2 :(得分:0)
必须在FROM子句中声明要在Where子句中使用的别名...您只需重命名一列,而不是实际重命名对象(如表)。
答案 3 :(得分:0)
使用此查询:
SELECT
o.order_id,
o.order_po_no,
o.order_ship_date,
acct.acct_company,
SUM( ROUND( i.item_qty * i.item_price, 2 ) ) AS item_amount,
trans_paid
FROM orders AS o
LEFT JOIN
(SELECT SUM( trans_amount ) AS trans_paid
FROM
WHERE trans_pending =0
AND trans_date >= '$from_date'
AND trans_date <= '$to_date'
) temp
USING order_id
INNER JOIN accounts AS acct ON o.acct_id = acct.acct_id
INNER JOIN items AS i ON o.order_id = i.order_id
WHERE (o.order_status =7 or o.order_status = 4)
AND trans_paid IS NOT NULL
AND acct.is_wholesale =1
AND acct.acct_company LIKE '%".$_POST['company']."%'
GROUP BY o.order_id