如何在mySQL中设置变量

时间:2017-07-06 20:35:00

标签: mysql sql

我有以下声明:

SELECT 
    start_date, 
    end_date,
    DATE(now()) BETWEEN start_date AND end_date should_be_live
FROM
    mytable
WHERE
    DATE(now()) BETWEEN start_date AND end_date should_be_live = 1

有没有办法设置变量should_be_live =表达式DATE(now()) BETWEEN start_date AND end_date。如果是这样,我该怎么做?

2 个答案:

答案 0 :(得分:2)

如果“变量”表示“结果集中的列”,则为“是”。你基本上是这样做的:

SELECT start_date, end_date,
       ( DATE(now()) BETWEEN start_date AND end_date) as should_be_live
FROM mytable;

如果使用“变量”,表示您要在select中定义一列,然后对其进行过滤,则不能使用where执行此操作(除非您使用子查询)。您可以使用having

SELECT start_date, end_date,
       ( DATE(now()) BETWEEN start_date AND end_date) as should_be_live
FROM mytable
HAVING should_be_live = 1;

having的这种使用是MySQL扩展。

答案 1 :(得分:1)

不幸的是,您必须在DATE(now()) BETWEEN start_date AND end_date子句中重复相同的表达式WHERE,除非您尝试在外部查询中访问它,例如

SELECT * FROM (
SELECT 
    start_date, 
    end_date,
    DATE(now()) BETWEEN start_date AND end_date as should_be_live
FROM mytable ) xxx
WHERE should_be_live = 1;

列别名只能由GROUP BYHAVINGORDER BY子句访问,而不能访问WHERE子句(对它来说是MySQL扩展而不是标准SQL) )