例如:
select count(*) as (select date_sub(curdate(),interval 4 day))
from userinfo
where createTime > (select date_sub(curdate(),interval 4 day));
这不起作用。它表示' as'之后的语法。是不正确的。我如何使这项工作?
我希望结果如下:
| |2016-01-14|
|-|----------|
|1| 1000 |
答案 0 :(得分:4)
使用普通的静态查询,您无法将列名定义为变量/子查询,但您可以使用动态SQL(prepared statements)来实现它:
SET @sql =
CONCAT('select count(*) as `',(select date_sub(curdate(),interval 4 day)),'` from userinfo where createTime > (select date_sub(curdate(),interval 4 day));');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
的 SqlFiddleDemo
强>
输出:
╔════════════╗
║ 2016-01-14 ║
╠════════════╣
║ 2 ║
╚════════════╝