我无法在计算列上写条件。我在Stackoverflow上看了几篇文章。不幸的是,我仍然无法弄明白。我有以下MySQL查询:
SELECT
c.pk_tbl_commodity, c.s_name, c.s_default_variant,
p.pk_tbl_parameter, p.s_name_parameter,
((SELECT SUM(p2.n_price_parameter) from tbl_Parameter p2
WHERE p2.fk_tbl_commodity = p.fk_tbl_commodity
AND p2.b_default = 1
AND p2.s_name_parameter <> p.s_name_parameter GROUP BY NULL) + c.n_price_without_dph + p.n_price_parameter) as total
FROM tbl_Commodity c JOIN tbl_Parameter p on (p.fk_tbl_commodity = c.pk_tbl_commodity)
WHERE s_name like '%acti%'
AND b_bin = '0'
AND total = 3340
ORDER BY s_name, s_default_variant;
我收到了错误:
[Err] 1054 - Unknown column 'total' in 'where clause'
如何在子查询和sum(列别名 total )的结果上添加条件?
谢谢。
答案 0 :(得分:3)
SELECT
列表中定义的别名无法在WHERE
列表中引用,只是因为查询执行的(逻辑)顺序为FROM -> WHERE -> GROUP BY -> (HAVING) -> SELECT
。
您可以尝试将AND total = 3340
替换为HAVING total = 3340
。
这不是标准的SQL,但它在MySQL中是允许的(它在执行HAVING
和SELECT
子句的顺序上是灵活的),并且可以避免重复{{{}中的代码。 1}}子句。
另一种方法是将查询封装在派生表中,并在外部WHERE
子句中提取条件。
所以你的选择是:
使用WHERE
(MySQL允许的技巧):
HAVING
SELECT
c.pk_tbl_commodity, c.s_name, c.s_default_variant,
p.pk_tbl_parameter, p.s_name_parameter,
(... long and complex subquery ...) AS total
FROM tbl_Commodity c JOIN tbl_Parameter p
on (p.fk_tbl_commodity = c.pk_tbl_commodity)
WHERE s_name like '%acti%'
AND b_bin = '0'
HAVING total = 3340
ORDER BY s_name, s_default_variant ;
和SELECT
子句中的重复代码:
WHERE
封装在派生表中:
SELECT
c.pk_tbl_commodity, c.s_name, c.s_default_variant,
p.pk_tbl_parameter, p.s_name_parameter,
(... long and complex subquery ...) AS total
FROM tbl_Commodity c JOIN tbl_Parameter p
on (p.fk_tbl_commodity = c.pk_tbl_commodity)
WHERE s_name like '%acti%'
AND b_bin = '0'
AND (... long and complex subquery ...) = 3340
ORDER BY s_name, s_default_variant ;
由于SELECT *
FROM
( SELECT
c.pk_tbl_commodity, c.s_name, c.s_default_variant,
p.pk_tbl_parameter, p.s_name_parameter,
(... long and complex subquery ...) AS total
FROM tbl_Commodity c JOIN tbl_Parameter p
on (p.fk_tbl_commodity = c.pk_tbl_commodity)
WHERE s_name like '%acti%'
AND b_bin = '0'
) AS dt
WHERE total = 3340
ORDER BY s_name, s_default_variant ;
列的结果不变(total
),您也可以使用(不重复代码):
3340
(如果条件是SELECT
c.pk_tbl_commodity, c.s_name, c.s_default_variant,
p.pk_tbl_parameter, p.s_name_parameter,
3340 AS total
FROM tbl_Commodity c JOIN tbl_Parameter p
on (p.fk_tbl_commodity = c.pk_tbl_commodity)
WHERE s_name like '%acti%'
AND b_bin = '0'
AND (... long and complex subquery ...) = 3340
ORDER BY s_name, s_default_variant ;
或者除了相等之外的任何其他条件,那当然不会起作用。)