2015-06-10 49 views
1

有沒有辦法在同一個查詢中引用MySQL查詢的各個部分?引用mySQL查詢組件

例如:

SELECT 50000 AS starting_principle, .065*50000 AS interest, 
    principle + interest AS principle_plus_interest 

第三列,principle_plus_interest查詢集給我一個錯誤。除了寫作50000 + .065*50000 AS principle_plus_interest之外,還有什麼方法可以編碼嗎?

回答

3

您不能引用select列表中的別名(或where子句,就此而言)。解決這個問題的一個方法是使用子查詢:

SELECT starting_principle, 
     interest, 
     principle + interest AS principle_plus_interest 
FROM (SELECT 50000 AS starting_principle, .065*50000 AS interest 
     FROM some_table) t 
+0

正在執行'50000 + .065 * 50000 AS principle_plus_interest'會比內聯視圖更好。 – Rahul

+1

其實,我認爲'選擇50000作爲starting_principle,0.065作爲興趣'應該在子查詢中。然後計算應該基於這些項目。 –