如何在 MySQL 中使用“WITH”子句?

Posted

技术标签:

【中文标题】如何在 MySQL 中使用“WITH”子句?【英文标题】:How do you use the "WITH" clause in MySQL? 【发布时间】:2010-11-25 20:05:30 【问题描述】:

我正在将我的所有 SQL Server 查询转换为 mysql,并且其中包含 WITH 的查询都失败了。这是一个例子:

WITH t1 AS
(
     SELECT article.*, userinfo.*, category.*
     FROM question
     INNER JOIN userinfo ON userinfo.user_userid = article.article_ownerid
     INNER JOIN category ON article.article_categoryid = category.catid
     WHERE article.article_isdeleted = 0
)
SELECT t1.*
FROM t1
ORDER BY t1.article_date DESC
LIMIT 1, 3

【问题讨论】:

你把那个查询弄傻了,对吧?根本没有理由在那里使用 CTE。 @NeilMcGuigan 天哪!这是我在这个网站上看到的最有趣的 cmets 之一(虽然它真的不是那么有趣,但是厚颜无耻!;))+1。 我认为这是一个相关或重复的问题Generating a series of dates @NeilMcGuigan 大部分托管服务只提供 MySQL 或 MariaDB,不考虑从 MySQL 迁移到 PostgreSQL 的麻烦,升级到 MySQL 8 或 MariaDB 10.2.1 会更容易 这个查询现在应该可以工作了(使用 MySQL 8.x),对吧? 【参考方案1】:

MySQL 8.0 之前的版本 doesn't support the WITH clause(SQL Server 中的 CTE;Oracle 中的子查询因子),因此您可以使用:

临时表 派生表 内联视图(实际上是 WITH 子句所代表的 - 它们是可互换的)

该功能的请求可以追溯到 2006 年。

如前所述,您提供了一个糟糕的示例 - 如果您不以任何方式更改列的输出,则无需执行子选择:

  SELECT * 
    FROM ARTICLE t
    JOIN USERINFO ui ON ui.user_userid = t.article_ownerid
    JOIN CATEGORY c ON c.catid =  t.article_categoryid
   WHERE t.published_ind = 0
ORDER BY t.article_date DESC 
   LIMIT 1, 3

这是一个更好的例子:

SELECT t.name,
       t.num
  FROM TABLE t
  JOIN (SELECT c.id
               COUNT(*) 'num'
          FROM TABLE c
         WHERE c.column = 'a'
      GROUP BY c.id) ta ON ta.id = t.id

【讨论】:

这里应该提到 CTE 通常支持递归——子查询无法做到这一点 这个问题是关于“模仿” MySQL 中的 CTE 支持——不能做的一件事是 CTE 在所有支持它的平台上的递归功能,这是我的观点。 是的。而且他们仍然没有在他们的发布分支中实现它。显然,他们在伦敦的 phpCONFERENCE2010 上“炫耀”了这个“功能”。对该错误报告的评论很能说明问题。 [2008 年 10 月 7 日 19:57] Stuart Friedberg:“Valeriy,你们一定有令人难以置信的积压。从提交请求到获得第一次确认之间的 33 个月是一段令人瞠目结舌的时间。感谢您考虑这个请求。 " 看起来这是被添加到mysql 8(链接仍然是bugs.mysql.com/bug.php?id=16244) 这个答案需要被杀死——在 2018 年,MySQL 现在支持 WITH 子句【参考方案2】:

Mysql 开发团队宣布 8.0 版将有Common Table Expressions in MySQL (CTEs)。因此可以编写如下查询:


WITH RECURSIVE my_cte AS
(
  SELECT 1 AS n
  UNION ALL
  SELECT 1+n FROM my_cte WHERE n<10
)
SELECT * FROM my_cte;
+------+
| n    |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
+------+
10 rows in set (0,00 sec)

【讨论】:

bugs.mysql.com/bug.php?id=16244(计划用于 8.0)+(递归 CTE 在 MySQL 8.0.1 和更新版本中)【参考方案3】:

在 Sql 中,with 语句指定一个临时命名的结果集,称为公用表表达式 (CTE)。它可用于递归查询,但在这种情况下,它指定为子集。如果 mysql 允许子选择,我会尝试

select t1.* 
from  (
            SELECT  article.*, 
                    userinfo.*, 
                    category.* 
            FROM    question INNER JOIN 
                    userinfo ON userinfo.user_userid=article.article_ownerid INNER JOIN category ON article.article_categoryid=category.catid
            WHERE   article.article_isdeleted = 0
     ) t1
ORDER BY t1.article_date DESC Limit 1, 3

【讨论】:

这里是CTE的初学者介绍thecodeframework.com/introduction-to-mysql-cte【参考方案4】:

我点击了 lisachenko 分享的链接,发现了另一个指向该博客的链接: http://guilhembichot.blogspot.co.uk/2013/11/with-recursive-and-mysql.html

这篇文章列出了模拟 SQL WITH 的两种用法的方法。关于这些如何工作以执行与 SQL WITH 类似的查询的非常好的解释。

1) 使用 WITH 这样您就不必多次执行相同的子查询

CREATE VIEW D AS (SELECT YEAR, SUM(SALES) AS S FROM T1 GROUP BY YEAR);
SELECT D1.YEAR, (CASE WHEN D1.S>D2.S THEN 'INCREASE' ELSE 'DECREASE' END) AS TREND
FROM
 D AS D1,
 D AS D2
WHERE D1.YEAR = D2.YEAR-1;
DROP VIEW D;

2) 递归查询可以使用存储过程来完成,该存储过程使调用类似于递归查询。

CALL WITH_EMULATOR(
"EMPLOYEES_EXTENDED",
"
  SELECT ID, NAME, MANAGER_ID, 0 AS REPORTS
  FROM EMPLOYEES
  WHERE ID NOT IN (SELECT MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IS NOT NULL)
",
"
  SELECT M.ID, M.NAME, M.MANAGER_ID, SUM(1+E.REPORTS) AS REPORTS
  FROM EMPLOYEES M JOIN EMPLOYEES_EXTENDED E ON M.ID=E.MANAGER_ID
  GROUP BY M.ID, M.NAME, M.MANAGER_ID
",
"SELECT * FROM EMPLOYEES_EXTENDED",
0,
""
);

这是代码或存储过程

# Usage: the standard syntax:
#   WITH RECURSIVE recursive_table AS
#    (initial_SELECT
#     UNION ALL
#     recursive_SELECT)
#   final_SELECT;
# should be translated by you to 
# CALL WITH_EMULATOR(recursive_table, initial_SELECT, recursive_SELECT,
#                    final_SELECT, 0, "").

# ALGORITHM:
# 1) we have an initial table T0 (actual name is an argument
# "recursive_table"), we fill it with result of initial_SELECT.
# 2) We have a union table U, initially empty.
# 3) Loop:
#   add rows of T0 to U,
#   run recursive_SELECT based on T0 and put result into table T1,
#   if T1 is empty
#      then leave loop,
#      else swap T0 and T1 (renaming) and empty T1
# 4) Drop T0, T1
# 5) Rename U to T0
# 6) run final select, send relult to client

# This is for *one* recursive table.
# It would be possible to write a SP creating multiple recursive tables.

delimiter |

CREATE PROCEDURE WITH_EMULATOR(
recursive_table varchar(100), # name of recursive table
initial_SELECT varchar(65530), # seed a.k.a. anchor
recursive_SELECT varchar(65530), # recursive member
final_SELECT varchar(65530), # final SELECT on UNION result
max_recursion int unsigned, # safety against infinite loop, use 0 for default
create_table_options varchar(65530) # you can add CREATE-TABLE-time options
# to your recursive_table, to speed up initial/recursive/final SELECTs; example:
# "(KEY(some_column)) ENGINE=MEMORY"
)

BEGIN
  declare new_rows int unsigned;
  declare show_progress int default 0; # set to 1 to trace/debug execution
  declare recursive_table_next varchar(120);
  declare recursive_table_union varchar(120);
  declare recursive_table_tmp varchar(120);
  set recursive_table_next  = concat(recursive_table, "_next");
  set recursive_table_union = concat(recursive_table, "_union");
  set recursive_table_tmp   = concat(recursive_table, "_tmp"); 
  # Cleanup any previous failed runs
  SET @str =
    CONCAT("DROP TEMPORARY TABLE IF EXISTS ", recursive_table, ",",
    recursive_table_next, ",", recursive_table_union,
    ",", recursive_table_tmp);
  PREPARE stmt FROM @str;
  EXECUTE stmt; 
 # If you need to reference recursive_table more than
  # once in recursive_SELECT, remove the TEMPORARY word.
  SET @str = # create and fill T0
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table, " ",
    create_table_options, " AS ", initial_SELECT);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  SET @str = # create U
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table_union, " LIKE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  SET @str = # create T1
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table_next, " LIKE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  if max_recursion = 0 then
    set max_recursion = 100; # a default to protect the innocent
  end if;
  recursion: repeat
    # add T0 to U (this is always UNION ALL)
    SET @str =
      CONCAT("INSERT INTO ", recursive_table_union, " SELECT * FROM ", recursive_table);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we are done if max depth reached
    set max_recursion = max_recursion - 1;
    if not max_recursion then
      if show_progress then
        select concat("max recursion exceeded");
      end if;
      leave recursion;
    end if;
    # fill T1 by applying the recursive SELECT on T0
    SET @str =
      CONCAT("INSERT INTO ", recursive_table_next, " ", recursive_SELECT);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we are done if no rows in T1
    select row_count() into new_rows;
    if show_progress then
      select concat(new_rows, " new rows found");
    end if;
    if not new_rows then
      leave recursion;
    end if;
    # Prepare next iteration:
    # T1 becomes T0, to be the source of next run of recursive_SELECT,
    # T0 is recycled to be T1.
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table, " RENAME ", recursive_table_tmp);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we use ALTER TABLE RENAME because RENAME TABLE does not support temp tables
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table_next, " RENAME ", recursive_table);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table_tmp, " RENAME ", recursive_table_next);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # empty T1
    SET @str =
      CONCAT("TRUNCATE TABLE ", recursive_table_next);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
  until 0 end repeat;
  # eliminate T0 and T1
  SET @str =
    CONCAT("DROP TEMPORARY TABLE ", recursive_table_next, ", ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # Final (output) SELECT uses recursive_table name
  SET @str =
    CONCAT("ALTER TABLE ", recursive_table_union, " RENAME ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # Run final SELECT on UNION
  SET @str = final_SELECT;
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # No temporary tables may survive:
  SET @str =
    CONCAT("DROP TEMPORARY TABLE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # We are done :-)
END|

delimiter ;

【讨论】:

【参考方案5】:

'Common Table Expression'这个功能在MySQL中是没有的,所以你必须去制作视图或者临时表来解决,这里我使用了临时表。

这里提到的存储过程将解决您的需求。如果我想获取我的所有团队成员及其关联成员,此存储过程将有所帮助:

----------------------------------
user_id   |   team_id
----------------------------------
admin     |   NULL
ramu      |   admin
suresh    |   admin
kumar     |   ramu
mahesh    |   ramu
randiv    |   suresh
-----------------------------------

代码:

DROP PROCEDURE `user_hier`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `user_hier`(in team_id varchar(50))
BEGIN
declare count int;
declare tmp_team_id varchar(50);
CREATE TEMPORARY TABLE res_hier(user_id varchar(50),team_id varchar(50))engine=memory;
CREATE TEMPORARY TABLE tmp_hier(user_id varchar(50),team_id varchar(50))engine=memory;
set tmp_team_id = team_id;
SELECT COUNT(*) INTO count FROM user_table WHERE user_table.team_id=tmp_team_id;
WHILE count>0 DO
insert into res_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
insert into tmp_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
select user_id into tmp_team_id from tmp_hier limit 0,1;
select count(*) into count from tmp_hier;
delete from tmp_hier where user_id=tmp_team_id;
end while;
select * from res_hier;
drop temporary table if exists res_hier;
drop temporary table if exists tmp_hier;
end

这可以使用:

mysql>call user_hier ('admin')//

【讨论】:

【参考方案6】:

该功能称为公用表表达式 http://msdn.microsoft.com/en-us/library/ms190766.aspx

您将无法在 mySQL 中执行确切的操作,最简单的方法可能是创建一个镜像该 CTE 的视图,然后从该视图中进行选择。您可以使用子查询来做到这一点,但这会表现得很糟糕。如果您遇到任何执行递归的 CTE,我不知道您如何在不使用存储过程的情况下重新创建它。

编辑: 正如我在评论中所说,您发布的示例不需要 CTE,因此您必须为问题简化它,因为它可以写成

SELECT article.*, userinfo.*, category.* FROM question
     INNER JOIN userinfo ON userinfo.user_userid=article.article_ownerid
     INNER JOIN category ON article.article_categoryid=category.catid
     WHERE article.article_isdeleted = 0
 ORDER BY article_date DESC Limit 1, 3

【讨论】:

@derobert:不正确。视图具有元数据(即CREATE/DROP VIEW),您可以授予视图权限。【参考方案7】:

我喜欢@Brad 对此thread 的回答,但想要一种方法来保存结果以供进一步处理(MySql 8):

-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion

-- Some boundaries 
set @startDate = '2015-01-01'
    , @endDate = '2020-12-31' ; 

-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as      -- this has to go _before_ the "with", Duh-oh! 
    WITH RECURSIVE t as (
        select @startDate as dt
      UNION
        SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
    )
    select * FROM t     -- need this to get the "with"'s results as a "result set", into the "create"
;

-- Exists?
select * from tmpDates ;

产生:

dt        |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|

【讨论】:

以上是关于如何在 MySQL 中使用“WITH”子句?的主要内容,如果未能解决你的问题,请参考以下文章

MySQL "WITH" 子句

如何在存储过程选择子句中使用 with 子句 CTE 表达式常见

如何在 mariadb 或 mysql 中创建临时表?

如何在标准 SQL 的 WHERE 子句中使用 WITH 子查询作为选项列表

如何使用SQL中的“With”子句更新值

如何在 Spring Data JPA 中使用 CTE 表达式 WITH 子句