How do you use the “WITH” clause in MySQL?

前端 未结 7 1265
耶瑟儿~
耶瑟儿~ 2020-11-22 04:02

I am converting all my SQL Server queries to MySQL and my queries that have WITH in them are all failing. Here\'s an example:

WITH t1 AS
(
              


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 05:01

    I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (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 ;
    
    

    Which produces:

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

提交回复
热议问题