表达式上的别名无法识别

时间:2014-04-09 17:20:24

标签: mysql sql

我在JAVA中编写的数据库值为NULL的演示代码片段。

我在其中使用NULL编写了一些简单的表达式,并为这些表达式提供了别名。但没有AS关键字。我很清楚它是可选的。

当我在MySQL命令行运行SQL查询并使用JAVA时,结果相同。

但奇怪的是,(虽然,它可能不适合你们中的一些人),我发现在其中一个表达式中它没有使用定义的别名,但是它使用了整个表达式和表达式名称,并使用了空格字符在他们之间。该空间是sql语句中表达式和别名之间的分隔符。

当我在同一个表达式上显式使用AS关键字时,结果与预期一致。

使用的SQL语句

select 
    length( null ) null_len -- to check if null data has any length
  , length( '' ) empty_len  -- to check length of an empty string
  , null = '' 'n=e?'        -- to check if null is equal to an empty string
  , null = '' "n=e?"        -- same as above but alias name within dbl quotes
  , null = '' as 'n=e??'    -- same with AS keyword on alias name used
  , '' is null 'e=n?'       -- to check if empty is equal to null
from dual;

MySQL命令行控制台上的结果

+----------+-----------+------------------+------------------+-------+------+
| null_len | empty_len | null = '' 'n=e?' | null = '' "n=e?" | n=e?? | e=n? |
+----------+-----------+------------------+------------------+-------+------+
|     NULL |         0 |             NULL |             NULL |  NULL |    0 |
+----------+-----------+------------------+------------------+-------+------+

使用Java ResultSetMetaData 的结果:

for( int i=1; i <= numberOfColumns; i++ ) {
  String columnLabel     = rsmd.getColumnLabel( i );
  String columnName      = rsmd.getColumnLabel( i );
  //String columnType      = rsmd.getColumnTypeName( i );
  //String columnClassName = rsmd.getColumnClassName( i );

  System.out.println( "Column Label: " + columnLabel );
  System.out.println( "Column Name : " + columnLabel );
  //System.out.println( "Column Type : " + columnType );
  //System.out.println( "Column Class: " + columnClassName );

  System.out.println();
} // for count of columns

输出

Column Label: null_len
Column Name : null_len

Column Label: empty_len
Column Name : empty_len

Column Label: null='' 'n=e?'
Column Name : null='' 'n=e?'

Column Label: null='' "n=e?"
Column Name : null='' "n=e?"

Column Label: n=e??
Column Name : n=e??

Column Label: e=n?
Column Name : e=n?

问题(可能不是!)

为什么不使用AS关键字识别别名名称? 这是一个众所周知的事实和问题吗?

注意:我使用过JAVA,只是为了测试和演示问题。问题不在于JAVA的行为。因此,答案不一定是JAVA具体的。

2 个答案:

答案 0 :(得分:1)

请参阅http://dev.mysql.com/doc/refman/5.6/en/string-literals.html

  

彼此相邻的引号字符串连接成一个字符串。

一个不明确的用法是允许我们将长字符串放入结果集中,但使列标题成为长字符串的较短前缀。很奇怪,但可能。我承认我从未使用过此功能。

mysql> select 'abc' 'def';
+--------+
| abc    |
+--------+
| abcdef |
+--------+

要执行您想要的操作,您可以使用AS关键字,也可以将别名作为分隔标识符替换为字符串文字。

mysql> select 'abc' `def`;
+-----+
| def |
+-----+
| abc |
+-----+

答案 1 :(得分:0)

似乎无论是撇号还是引号都不是转义列名称的好方法。我的建议是使用严重的口音,它似乎在所有情况下都能正常工作:

select 
    length( null ) null_len -- to check if null data has any length
  , length( '' ) empty_len  -- to check length of an empty string
  , null = '' `n=e?`        -- to check if null is equal to an empty string
  , null = '' as `n=e??`    -- same with AS keyword on alias name used
  , '' is null `e=n?`       -- to check if empty is equal to null

Here结果显示在SQL Fiddle中。有关此问题的更多详细信息,请参见here

相关问题