数据库表结构
产品表 product产品id 产品目录 产品名称
productid cids productname
1 (1,3,4) 精品服装1
2 (3,8) 精品服装2
3 (7,4,9) 精品服装3
需求:
1、比如进入一个产品的页面,通过url得到productid,如何通过productid 得到cids
现需要写个语句,找到product表中,与cids 有相同的所有产品比如通过url得到了productid值为1,那么cids值为(1,3,4),要找出product表中只要含有 1或3或4的所有产品mysql php
产品表 product产品id 产品目录 产品名称
productid cids productname
1 (1,3,4) 精品服装1
2 (3,8) 精品服装2
3 (7,4,9) 精品服装3
需求:
1、比如进入一个产品的页面,通过url得到productid,如何通过productid 得到cids
现需要写个语句,找到product表中,与cids 有相同的所有产品比如通过url得到了productid值为1,那么cids值为(1,3,4),要找出product表中只要含有 1或3或4的所有产品mysql php
select cids from product where productid = xxxx得到的结果,比如是(1,3,4)在PHP中拆成数组,然后数据库中查询select productid from product where ','+cids+',' like '%,1,%'
union
select productid from product where ','+cids+',' like '%,3,%'
union
select productid from product where ','+cids+',' like '%,4,%'不直接like,而前后加逗号的原因是如果是12,13,14也会like1成功另外这个写法如果表大了会很慢,因为会全表扫描,所以我还是建议你把表结构改一下。
from product
where find_in_set((select cids from product where productid = '$productid'), cids)
未经测试,如果不行,则先根据$productid查询出$cids,然后用$cids代替find_in_set函数的第一个参数即可。
如2楼所说,如果表记录很大,那么可能会很慢,建议还是改一下表结构。把productid和cid用单独一个表来记录对应关系,做好索引。
即形如 (1,3,4) 的改为形如 1,3,4 的
然后使用自连接,连接条件使用 find_in_set 函数计算
select T1.* from product T1, product T2 where find_in_set(T1.productid, T2.cids) and 2.productid=1