变量AS(SELECT ...)SQL

时间:2018-12-24 11:44:31

标签: mysql sql

这是一个非常愚蠢的问题,但是我一直不停地抨击自己,我什至不知道到底是什么给谷歌。

我有一个数据库,并且正在执行一些SQL查询。这个很好用。

SELECT 
year(datetime_buy), 
month(datetime_buy), 
count(distinct email) AS number
FROM ticket
WHERE year(datetime_buy)=2018
AND email IN (
    SELECT DISTINCT email 
    FROM ticket 
    WHERE Month(datetime_buy)=1
    AND Year(datetime_buy)=2018 AND datetime_cancel IS NULL)
GROUP BY 1, 2;

但是当我尝试为将来保存一些SELECT(例如jan_tickets)时:

jan_tickets AS (
SELECT DISTINCT email 
FROM ticket 
WHERE Month(datetime_buy)=1
AND Year(datetime_buy)=2018
AND datetime_cancel IS NULL),

SELECT
year(datetime_buy),
month(datetime_buy),
count(distinct email) AS number
FROM ticket
WHERE year(datetime_buy)=2018
AND email IN jan_tickets
GROUP BY 1, 2;

我遇到错误:

Error SQL (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 'jan_tickets AS (SELECT DISTINCT email FROM ticket
WHERE Month(datetime_buy)=1 AN' at line 1

更新:我使用MySQL 5.6。

1 个答案:

答案 0 :(得分:1)

假设您正在运行MySQL 8+,则对您的以下更新将起作用:

WITH jan_tickets AS (
    SELECT DISTINCT email
    FROM ticket
    WHERE DATE_FORMAT(datetime_buy, '%Y-%m') = '2018-01' AND datetime_cancel IS NULL
)

SELECT
    YEAR(datetime_buy),
    MONTH(datetime_buy),
    COUNT(DISTINCT email) AS number
FROM ticket
WHERE
    YEAR(datetime_buy) = 2018 AND
    email IN (SELECT email FROM jan_tickets)
GROUP BY 1, 2;

此处的注释包括CTE定义必须开始使用WITH。后面的子序列CTE不使用WITH,但应以逗号分隔。在最后一个CTE定义之后,使用它的查询之前没有逗号。在您的情况下,您需要在WHERE子句中使用子查询,该子查询从CTE中选择电子邮件。

编辑:

由于仅使用MySQL 5.6,因此不能使用通用表表达式。因此,我们可以内联CTE中包含的子查询:

SELECT
    YEAR(datetime_buy),
    MONTH(datetime_buy),
    COUNT(DISTINCT email) AS number
FROM ticket
WHERE
    YEAR(datetime_buy) = 2018 AND
    email IN (
        SELECT DISTINCT email
        FROM ticket
        WHERE DATE_FORMAT(datetime_buy, '%Y-%m') = '2018-01' AND
              datetime_cancel IS NULL
    )
GROUP BY 1, 2;