今天在写无限级分类
有这么一个字段:ArrayChild,存放ClassID列表(当前类别的所有子类别孙类别),形式是这样的“1,2,3,5,6”
目的就是在查询时获取ClassID的时候,直接跟ArrayChild字段里的内容匹配就可以了。
这样就在查询的时候,省去很多步骤。举例:
一级1,2,3
二级2,3
三级3
比如获取的ClassID为1时,那么其下面的所有的类别都能查到
直接select title from news where ClassID in (select ArrayChild from news_class where ClassID=1)
结果select title from news where ClassID in (1,2,3)添加的时候在论坛发了个贴,如何在SQL语句里连接字符串,问题解决。用的是concat
$conn->sql = "update news_class set ArrayChild=concat(ArrayChild,'," . $ClassID . "') where instr(concat(',',ArrayChild),'," . $ParentID . "') > 0";
但删除的时候这么写的
$conn->sql = "update news_class set ArrayChild=concat(Left(ArrayChild,instr(ArrayChild,'," . $row["ClassID"] . "')-1),mid(ArrayChild,instr(ArrayChild,'," . $row["ClassID"] . "')+length('," . $row["ClassID"] . "')))  where instr(concat(',',ArrayChild),'," . $row["ClassID"] . "') > 0";
我花了一个多小时
后来我浏览了下帖子列表,看到一篇帖子,点进去一看,原来有replace函数。我这时真想跳楼,费了那么大劲,人家一个函数就解决了,后来我改了下:
$conn->sql = "update news_class set ArrayChild=replace(ArrayChild,'," . $row["ClassID"] . "','') where instr(concat(',',ArrayChild),'," . $row["ClassID"] . "') > 0";感谢那位前辈。也许看了这篇帖子的人,会有所收获。特别是做无限分类的时候。
写的不是很清楚,请原谅。

解决方案 »

  1.   

    replace(ArrayChild,'," . $row["ClassID"] . "','')这样删头尾两个的时候似乎有问题?似乎应该这样?
    replace(concat(',',ArrayChild,','),'," . $row["ClassID"] . "','')
      

  2.   

    一楼写的有道理
    但我外面有个条件,如果是二级或三级目录的话,才执行
    if ($row["Depth"] > 0)
    {
    $conn->sql = "update news_class set ArrayChild=replace(ArrayChild,'," . $row["ClassID"] . "','') where instr(concat(',',ArrayChild),'," . $row["ClassID"] . "') > 0";
    }
    所以我当时调的时候没发现,虽然这么写最终执行的时候没错,但还是你说的,在ArrayChild前面加个","符号。
      

  3.   

    3楼
    我说的问题是,我做替换的时候写了好多代码,其实用replace一个函数就能解决的。