MySQL 查询时,查询条件有很多。一个目录树表,获取了 N 个节点,需要循环判断每个节点是否有子节点。由于数据库用的外网(不在同一个局域网内),当节点很多时(超过 500),效率很低,因为需要进行 500 次分次查询。
数据库的组织方式:
| 字段 | 名称 |
|---|---|
| pg_id | Id 号 |
| pg_name | 节点名称 |
| parent_id | 父节点Id号 |
select count(*) from os_pgroup where parent_id = 0select count(*) from os_pgroup where parent_id = 21select count(*) from os_pgroup where parent_id = 31select count(*) from os_pgroup where parent_id = 40xxxxxx
内网
如果是内网,直接使用应用程序进行循环调用 MySQL 即可,因为此时不会因为网络原因导致性能很低
外网
目前的应用场景,可以考虑使用
group by
SELECT count(*), parent_id from os_pgroup where parent_id in (10, 21, 31, 40, xxx) GROUP BY parent_id
结果如下:
| count(*) | parent_id |
|---|---|
| 0 | 35 |
| 21 | 14 |
| 31 | 1 |
这样有子节点的记录,就可以查询出来了。
如果查询条件过于复杂,可以考虑使用视图、存储过程(不建议使用)等方式解决
文章转载自郎涯技术,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




