MySQL CTE递归查询 Data too long for colum‘xxx‘ at row 1

在mysql 8 使用 CTE递归查询时,出现了这个报错

WITH recursive area AS (
 SELECT
 area_name, 
 area_code
 FROM
 sys_area_tree
 WHERE
 area_category = '1'
 AND parent_code IS NULL UNION ALL
 SELECT
 concat( t1.area_name, '/', t.area_name ),
 t.area_code
 FROM
 sys_area_tree t
 INNER JOIN area t1 ON t.parent_code = t1.area_code
 AND t.area_category = '1'
) 
select * from  area

原因:

是因为参与递归concat的【area_name】字段超出了长度限制,也就是说在非递归语句中,一开始【area_name】字段的长度就确定了

解决方案:

在cte表达式中非递归的查询语句中,将初始字段的长度重新转换一下,cast(xxx as CHAR(1024)) area_name

将sql 修改为:

WITH recursive area AS (
SELECT
cast( area_name AS CHAR ( 1024 )) area_name,
area_code
FROM
sys_area_tree
WHERE
area_category = '1'
AND parent_code IS NULL UNION ALL
SELECT
concat( t1.area_name, '/', t.area_name ),
t.area_code
FROM
sys_area_tree t
INNER JOIN area t1 ON t.parent_code = t1.area_code
AND t.area_category = '1') 
select * from area

参考:https://dev.mysql.com/doc/refman/8.0/en/with.html

=====================================分割线==================================================

1、递归查询出来的字段,用于条件查询

报错:Illegal mix of collations (utf8mb4_bin,NONE) and (utf8mb4_general_ci,COERCIB.........

明显字符集问题;使用 convert 函数(可自行搜索)

CONVERT(expr USING transcoding_name)

例如:CONVERT(xxx  USING utf8)

 

posted @ 2023-10-23 14:00  唏嘘-  阅读(328)  评论(0编辑  收藏  举报