mysql 5.6 是否支持 [ with.. as() ] 语法?

时间:2021-02-04 02:20:36

标签: mysql

navicat picture

with detail as(
select id,end_time,status from t_wl_record_repairs_detail where end_time is null
)
select COUNT(1) as sum, 'today' as name from detail where end_time is not null and end_time >= '2021-02-04 00:00:00' and `status` > 2
UNION
select COUNT(1) , 'd1' as name from detail where end_time is not null and end_time < '2021-02-04 00:00:00' and `status` < 3
UNION
select COUNT(1), 'd7' as name from detail where end_time is not null and end_time < '2021-01-29 00:00:00' and `status` < 3
UNION
select COUNT(1), 'd30' as name from detail where end_time is not null and end_time < '2021-01-06 00:00:00' and `status` < 3;

我想这样写sql,但是不行。mysql 5.6支持[with..as()]语法吗?

1 个答案:

答案 0 :(得分:1)

不,Common Table ExpressionsWITH 子句的名称)是在 MySQL 8 中引入的。它们不能在 5.6 中使用。相反,我们通常会加入旧 MySQL 版本中的子查询。

对于像您这样的查询,您在多个 UNION 组件中重用相同的公共表表达式,而不是子查询,我建议将其选择到一个临时表中,然后在您的 UNION查询。

CREATE TEMPORARY TABLE detail 
  SELECT id, end_time, status
  FROM t_wl_record_repairs_detail
  WHERE end_time IS NULL;

SELECT COUNT(1) as sum, 'today' as name FROM detail...
UNION
SELECT COUNT(1) as sum, 'd1' as name....
UNION...

更新:

MySQL has documented 表明不能多次引用临时表,例如在 UNION 中。

使用巧妙的 CASE 链并且没有临时表或 CTE,这仍然是可行的。

SELECT
  COUNT(1) AS sum,
  CASE 
    WHEN end_time end_time >= '2021-02-04 00:00:00' and `status` > 2 THEN 'today'
    WHEN end_time < '2021-02-04 00:00:00' and `status` < 3 THEN 'd1'
    WHEN end_time < '2021-01-29 00:00:00' and `status` < 3 THEN 'd7'
    WHEN end_time < '2021-01-06 00:00:00' and `status` < 3 THEN 'd30'
    ELSE 'other'
  END AS name
FROM t_wl_record_repairs_detail
GROUP BY name