如何将使用WITH子句的SQL查询转换为MySQL?

时间:2015-07-03 22:36:23

标签: mysql

如何将其转换为MySQL? 它使用MySQL不支持的WITH子句。我搜索了网站并阅读了几个问题但没有帮助。

我还在学习SQL,所以不太了解:/。

此查询将四列中的数据合二为一。

WITH query AS (
  SELECT t1.categoryid AS lev1, t2.categoryid as lev2, t3.categoryid as lev3, t4.categoryid as lev4
  FROM category AS t1
  LEFT JOIN category AS t2 ON t2.parent = t1.categoryid
  LEFT JOIN category AS t3 ON t3.parent = t2.categoryid
  LEFT JOIN category AS t4 ON t4.parent = t3.categoryid
  WHERE t1.categoryid = 4149418031)
SELECT lev1 AS category_value FROM query
  UNION
SELECT lev2 AS category_value FROM query
  UNION
SELECT lev3 AS category_value FROM query
  UNION
SELECT lev4 AS category_value FROM query;

2 个答案:

答案 0 :(得分:4)

有几种方法。我建议在cross join中使用select和条件:

SELECT DISTINCT (case when n.n = 1 then t1.categoryid 
                      when n.n = 2 then t2.categoryid
                      when n.n = 3 then t3.categoryid 
                      when n.n = 4 then t4.categoryid
                 end) as category_value
FROM category t1 LEFT JOIN
     category t2
     ON t2.parent = t1.categoryid LEFT JOIN
     category t3
     ON t3.parent = t2.categoryid LEFT JOIN
     category t4
     ON t4.parent = t3.categoryid CROSS JOIN
     (select 1 as n union all select 2 union all select 3 union all select 4) n
WHERE t1.categoryid = 4149418031;

答案 1 :(得分:3)

var chr=''; for (var num=0; num <8; num++){ for (var num_1=0; num_1 <=3; num_1++){ if (num%2 == 0) chr += "# "; else chr +=" #"; } console.log(chr) chr = ''; } 为查询创建(有效)临时表,因此一种方法是:

WITH