Mysql CAST(CONCAT_WS试图获得正确的语法

时间:2013-10-20 17:57:17

标签: mysql

这有效

SELECT EntryId FROM 2_1_journal 
WHERE CAST(CONCAT_WS('-', RecordYear,RecordMonth,RecordDay) AS DATE) = ? 

但希望在WHERE之前为列名称的日期定义“虚拟”列名称,例如RecordDate

尝试

SELECT EntryId FROM 2_1_journal 
CAST(CONCAT_WS('-', RecordYear,RecordMonth,RecordDay) AS DATE) RecordDate 
WHERE RecordDate = ?


SELECT EntryId FROM 2_1_journal 
CAST(CONCAT_WS('-', RecordYear,RecordMonth,RecordDay) AS DATE) AS RecordDate 
WHERE RecordDate = ?


SELECT EntryId FROM 2_1_journal 
CAST((CONCAT_WS('-', RecordYear,RecordMonth,RecordDay) AS DATE) AS RecordDate) 
WHERE RecordDate = ?

在所有情况下都会收到错误Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CAST

请告知什么是正确的synatax

1 个答案:

答案 0 :(得分:1)

http://dev.mysql.com/doc/refman/5.5/en/select.html

  

“不允许在WHERE子句中引用列别名,因为在执行WHERE子句时可能尚未确定列值。参见第C.5.5.4节,Problems with Column Aliases。“

如果你想选择 WHERE子句中的操作结果作为列值,那么你将必须编写该操作两次 - 一次在WHERE子句中,没有别名,以及SELECT之后的列列表。