mysqlcommon-table-expressionwith-clausesubquery-factoringmysql-8.0

How do you use the "WITH" clause in MySQL?


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
(
     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

Solution

  • 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:

    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