添加具有别名值的条件

时间:2019-02-25 12:51:06

标签: mysql sql

我尝试添加其他条件

SELECT
   ROUND(SUM((cus.amount_product/1000)),1) as TOTAL_N,
   ROUND(SUM((cus.amount_product/1000)),1) as TOTAL_PRODUCT
FROM customs AS cus
LEFT JOIN customs_products AS cp ON cp.id = cus.customs_product_id
   WHERE cp.product IN (101,103,104,106)
   AND TOTAL_PRODUCT  >= 1

问题出在此TOTAL_PRODUCT中。我试图通过多种方式做到这一点:

1. AND (ROUND(SUM((cus.amount_product/1000)),1)) > 1 --> NOT WORKING
2. AND TOTAL_PRODUCT  >= 1 --> NOT WORKING

你能帮我吗?我在做什么

3 个答案:

答案 0 :(得分:1)

HAVING子句可以满足您的要求,但您的查询没有任何意义。您有两次相同的表达式。即使这是一个错字,WHERE子句也将LEFT JOIN变成了内部联接。我怀疑您可能真的想要:

SELECT COUNT(cus.customs_product_id) as TOTAL_N,
       ROUND(SUM((cus.amount_product/1000)), 1) as TOTAL_PRODUCT
FROM customs_products cp LEFT JOIN
     customs cus
     ON cp.id = cus.customs_product_id
WHERE cp.product IN (101, 103, 104, 106)
HAVING TOTAL_PRODUCT >= 1;

我怀疑您实际上也可能在查询中需要GROUP BY

答案 1 :(得分:0)

使用having,因为它使用聚合函数,因此无法在where clause中使用

SELECT
   ROUND(SUM((cus.amount_product/1000)),1) as TOTAL_N,
   ROUND(SUM((cus.amount_product/1000)),1) as TOTAL_PRODUCT
FROM customs AS cus
LEFT JOIN customs_products AS cp ON cp.id = cus.customs_product_id
   WHERE cp.product IN (101,103,104,106)
having ROUND(SUM((cus.amount_product/1000)),1)>= 1

答案 2 :(得分:0)

使用具有组过滤器的

SELECT
   ROUND(SUM((cus.amount_product/1000)),1) as TOTAL_N,
   ROUND(SUM((cus.amount_product/1000)),1) as TOTAL_PRODUCT
FROM customs AS cus
LEFT JOIN customs_products AS cp ON cp.id = cus.customs_product_id
   WHERE cp.product IN (101,103,104,106)
  having TOTAL_PRODUCT  >= 1

TOTAL_PRODUCT是聚合列的别名,因此您需要拥有