2015-11-15 22 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