SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade ,c.sort_order, COUNT( s.cat_id ) AS has_children FROM ecs_category AS c LEFT JOIN ecs_category AS s ON s.parent_id = c.cat_id GROUP BY c.cat_id ORDER BY c.parent_id, c.sort_order ASC
用左连接连接一个表,返回一个字段 has_children,这个字段是记录有多少子节点。
看看代码吧,
代码如下
复制代码
public function getCategory($catid=0,$re_type = true,$selected=0) { $db = new Public_DataBase(); $sql = ‘select c.cid,c.catename,c.catetype,c.ctime,c.parentid,count(s.cid) as has_children from ‘. __MYSQL_PRE.’category as c left join ‘. __MYSQL_PRE.’category as s on s.parentid=c.cid group by c.cid order by c.parentid asc’; $res = $db->selectTable($sql); $cateInfo = self::getChildTree($catid,$res); if($re_type==true) { $select = ”; foreach($cateInfo as $val) { $select .= ‘<option value="' . $val['cid'] . '" '; $select .= ($selected == $val[‘cid’]) ? “selected=’ture'” : ”; $select .= ‘>’; if($val[‘level’]>0) { $select .= str_repeat(‘ ‘, $val[‘level’] * 4); } $select .= htmlspecialchars(addslashes($val[‘catename’]), ENT_QUOTES) . ”; } return $select; }