dongzantai7570 2014-02-24 22:34
浏览 530
已采纳

MySQL匹配LIKE或REGEX的数字列表

I can't quite figure out the best way to search for matching numbers in my MySQL database.

Currently my query ends up as:

SELECT count(*) AS total FROM `videos_test` WHERE `channels` LIKE '%$cid%';

$cid can be any integer and the channels is in the format, "chan1,chan2,chan3,..." with any number of (even 0) channels set. Some valid strings would be:

1,12,5
5

8,1,2

The problem is that when $cid=2, I get back the rows that contain any 2, even as part of a larger number (12,32,25,...). It looks like I can do this with REGEX or MATCH/AGAINST, but I'm very confused about the syntax. Could someone point me in the right direction?

  • 写回答

1条回答 默认 最新

  • douwen5690 2014-02-24 22:45
    关注

    Using like you would fix this as:

    SELECT count(*) AS total
    FROM `videos_test`
    WHERE concat(',', channels, ',') LIKE '%,$cid,%';
    

    Another way to do this in MySQL is:

    SELECT count(*) AS total
    FROM `videos_test`
    WHERE find_in_set($cid, channels) > 0;
    

    As mentioned in the comment, you seem to be storing lists of things in a column. This is a bad idea. You should create an association/junction table with one row per video and channel combination.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器