2015-11-15 21 views
2

在我的CREATE VIEW的字符串和長度的毗連我想:MySQL的:選擇造成的毗連

SELECT CONCAT(t.str1, t.str2) AS Title, CHAR_LENGTH(Title) AS Length 

但本病產生錯誤:

Unknown column 'Title' in 'field list'.

是什麼做的正確方法這不必Concat相同的字符串兩次?

回答

0

您不能引用您在SELECT創建的別名,使用表達式來代替:

SELECT sub.Title, CHAR_LENGTH(sub.Title) AS Length 
FROM (
    SELECT CONCAT(t.str1, t.str2) AS Title 
    FROM table_name t 
) AS sub; 

All-at-once operation

"All-at-Once Operations" means that all expressions in the same logical query process phase are evaluated logically at the same time.

SELECT CONCAT(t.str1, t.str2) AS Title, 
     CHAR_LENGTH(CONCAT(t.str1, t.str2) ) AS Length 
FROM table_name t 

如果需要,您可以使用子查詢

和:

We cannot use an alias in next column expression in the SELECT clause. In the query we create a corrected first name and we want to use it in next column to produce the full name, but the All-at-Once operations concept tells us you cannot do this because all expressions in the same logical query process phase (here is SELECT) are evaluated logically at the same time.

+0

但是SQL引擎會優化這個嗎所以不要每行執行兩次Conntic操作? – Pirs01

+0

@ Pirs01使用第一個版本並停止擔心性能 – lad2025

+0

但是,如果我在創建視圖中使用子查詢,那麼我將不再使用MERGE算法,因此在性能方面不能成爲我的最佳選擇?編輯:我想我已經沒有使用它,因爲我用CONCAT和CHAR_LENGTH – Pirs01