有這么一個需求,查出分類中沒有子分類的一級分類,腦海中首次出現的解決思路和這樣的
- 先使用PHP查出所有的一級分類
- 遞歸查詢一級分類是否有子分類
- 將沒有子分類的一級分類匯總
但覺的這樣處理太麻煩了,然后轉而在數據庫層面上想辦法,最后利用Mysql提供的replace、length方法完美解決
select name,term_id,parent,path from terms where status = 1 and parent = 0 --僅一級分類 --過濾掉沒有子分類的分類 --length(path)-length(replace(path,'-','')) 統計path列字符串中’-‘出現的次數 --大於1表明至少有兩個父分類 and term_id not in(select parent from terms where length(path)-length(replace(path,'-',''))>1) order by listorder asc,term_id asc
參考:
