V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
s2555
V2EX  ›  程序员

问个 sql 查询语句,部分内容匹配

  •  
  •   s2555 · 2014-12-16 10:48:39 +08:00 · 3842 次点击
    这是一个创建于 3419 天前的主题,其中的信息可能已经有所发展或是发生改变。
    假设我字段内容是 ids=1,2,3,4,我要查询的字符串是 5,2,3,6,他们只有2,3相同,这么查询出来?
    我能想到的只有 ids like '5' or ids like '2' ids like '3' ids like '6' ,有没有更好的办法?
    15 条回复    2014-12-16 17:45:55 +08:00
    mhycy
        1
    mhycy  
       2014-12-16 11:18:47 +08:00
    字符串已知的话用IN
    ids IN ("5","2","3","6")
    Cynic222
        2
    Cynic222  
       2014-12-16 11:22:27 +08:00
    你这样用"like"等于用"="
    l1905
        3
    l1905  
       2014-12-16 13:05:12 +08:00
    ids 字符串前后都加逗号, ids='1,2,3,4' => ids=',1,2,3,4,'
    查询语句: ids like '%,5,%' or ids like '%,2,%' or ids like '%,3,%' or ids like '%,6,%'
    s2555
        4
    s2555  
    OP
       2014-12-16 13:51:55 +08:00
    @mhycy 这样行吗?我只用过当ids值是一个的情况,像现在 1,2,3,4的没有用过。

    @l1905 跟我想的一样啊,当然你这个是最恰当的。
    konakona
        5
    konakona  
       2014-12-16 13:55:12 +08:00
    比如你有一笔数据
    $ids = '1,2,3,7,8,65,32,12,32,55'
    你可以执行:
    select * from tablename where id in ('{$ids}');

    //select * from tablename where id in('1,2,3,7,8,65,32,12,32,55');
    s2555
        6
    s2555  
    OP
       2014-12-16 14:02:18 +08:00
    可能我表达还不清楚,是这样的:
    表结构
    id : 1
    value:1,2,3,4
    要用值=5,2,3,4 去把这个数据查询出来
    难道select * from 表 where value in(5,2,3,4) 这样吗?
    mhycy
        7
    mhycy  
       2014-12-16 14:03:29 +08:00
    @s2555 还以为你那个ids是一个列,原来列的值就是1,2,3啊..这么建表合适么..囧
    s2555
        8
    s2555  
    OP
       2014-12-16 14:30:05 +08:00
    @mhycy 那是数字相当于人的编号,这样设计已经定了好久了,现在这样想办法去查
    123123
        9
    123123  
       2014-12-16 16:17:15 +08:00
    @l1905 你这样任意值排在第一个怎么搜到?
    @s2555 把 LIKE 换成 FIND_IN_SET
    holystrike
        10
    holystrike  
       2014-12-16 16:30:57 +08:00
    把 5,2,3,6 拆成4个条件, 取 or 串在一起
    select * from table where
    find_in_set(5, 字段名) OR
    find_in_set(2, 字段名) OR
    find_in_set(3, 字段名) OR
    find_in_set(6, 字段名)
    holystrike
        11
    holystrike  
       2014-12-16 16:31:50 +08:00
    但是效率很低
    如果可能的话,重新设计表吧
    s2555
        12
    s2555  
    OP
       2014-12-16 16:43:29 +08:00
    @holystrike 这样的话用 like 就可以啦,看来只能这样的了。谢谢大家
    holystrike
        13
    holystrike  
       2014-12-16 16:58:32 +08:00
    @s2555 like 不行吧,逗号怎么办?
    l1905
        14
    l1905  
       2014-12-16 17:06:25 +08:00
    @123123 ids的值格式只能为',xxx,yyy,' or ',xxxx,' 值收尾必须是','
    123123
        15
    123123  
       2014-12-16 17:45:55 +08:00
    @l1905 这不能由你来规定啊…
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4342 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:07 · PVG 18:07 · LAX 03:07 · JFK 06:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.