2014-02-13 102 views
0

我無法在計算列上寫入條件。我已經閱讀了Stackoverflow上的一篇文章。不幸的是,我仍然無法弄清楚。我有以下MySQL查詢:在計算列上使用子句WHERE(包括子查詢)

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' 

我怎麼能在子查詢和總和(列別名)的結果添加條件?

謝謝。

回答

3

SELECT列表中定義的別名無法在WHERE列表中引用,只是因爲查詢的(邏輯)執行順序是FROM -> WHERE -> GROUP BY -> (HAVING) -> SELECT

雖然您可以嘗試用HAVING total = 3340替換AND total = 3340

這不是標準的SQL,但它允許在MySQL(這是的HAVINGSELECT條款的執行順序靈活),並會救你脫離WHERE子句中複製的代碼。

另一種方法是將查詢封裝在派生表中,並在外部WHERE子句中提取條件。

那麼你的選擇是:

  • 使用HAVING(招在MySQL允許):在SELECTWHERE條款

    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 
        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 ; 
    

(如果條件爲0,那當然不會工作或其他任何東西,但平等。)