-- FIND_IN_SET(id,str)可以查询出str字符串包含的id集合 SELECT * FROM region where FIND_IN_SET(id,'340100,340200')>0; -- GROUP_CONCAT(id)把所有查询的id形成一个字符串:id1,id2,id3... SELECT GROUP_CONCAT(id) FROM region where FIND_IN_SET(pid,'340100')>0;
-- 创建函数方便调用,实现传入一个父id查询所有子集区域 -- 思路:通过id查询他的子id集合,循环查询所有子id的子id,直到子id为空 CREATE PROCEDURE `getRegionByPid`( IN regionId int(11)) BEGIN DECLARE pIds VARCHAR(4000); DECLARE childIds VARCHAR(4000); -- 存放所有父id: id1,id2,id3... SET pIds = ''; -- 存放每次查询来的子id集合: id1,id2,id3... SET childIds = CAST(regionId AS CHAR); -- 循环查询 WHILE childIds is not NULL DO SET pIds = CONCAT(pIds,',',childIds); -- 查询childIds的子id集合 SELECT GROUP_CONCAT(id) INTO childIds FROM region WHERE FIND_IN_SET(pid,childIds) > 0 ; END WHILE; -- 查询所有子集 SELECT * FROM region WHERE FIND_IN_SET(id,pIds); END -- 直接调用就可以了 CALL getRegionByPid(340200);
省市区sql脚本
https://blog.csdn.net/qq_42145865/article/details/116899036