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

前端 未结 7 1100
耶瑟儿~
耶瑟儿~ 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:03

    MySQL prior to version 8.0 doesn't support the WITH clause (CTE in SQL Server parlance; Subquery Factoring in Oracle), so you are left with using:

    • TEMPORARY tables
    • DERIVED tables
    • inline views (effectively what the WITH clause represents - they are interchangeable)

    The request for the feature dates back to 2006.

    As mentioned, you provided a poor example - there's no need to perform a subselect if you aren't altering the output of the columns in any way:

      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
    

    Here's a better example:

    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
    
    0 讨论(0)
提交回复
热议问题