zoukankan      html  css  js  c++  java
  • 关于MySQL——find_in_set()函数的使用

    一、背景

    在做电商项目时,会遇到这样的一种情况,mysql数据库中商品表tb_product里面有个字段type,它存储的是商品类型,比如:

    1:热门推荐;

    2:精选推荐;

    3:品牌商品等。

    有些商品既属于热门推荐,也属于精选推荐,同时还是品牌商品,系统中type中用 1,2,3 这样的格式存储。

    这时业务人员希望你帮忙导出今日所有type中有3品牌商品的商品,你会怎么做?

    这时find_in_set函数就派上用场了。

    select * from tb_article where find_in_set('3',type);

    二、find_in_set函数的语法

    FIND_IN_SET(str,strlist)

    str 要查询的字符串

    strlist 字段名 参数以”,”分隔 如 (1,2,6,8)

    查询字段(strlist)中包含(str)的结果,返回结果为null或记录。

    例子:

    mysql> SELECT FIND_IN_SET('b', 'a,b,c,d'); 

    -> 2 因为b 在strlist集合中放在2的位置 从1开始。

    二、常见用法

    1、find_in_set() 和 in 的区别:

    FIND_IN_SET(str,strlist) 

    strlist是常量,则可以直接用IN

    例子:

    select * from user where user_id in (1,2,3); ----可以用IN。

    select * from user where user_id in (list); ---不可用,返回为空。list为一个变量。

    select * from user where user_id  find_in_set('1',list);-- 可用,正确返回。

    2、find_in_set() 和 like的区别:

    like是广泛的模糊匹配,字符串中没有分隔符,Find_IN_SET 是精确匹配,字段值以英文”,”分隔

    例子:

    SELECT * FROM users WHERE limits LIKE '%2%';



  • 相关阅读:
    topcoder srm 633 div1
    HDU 4997 Biconnected (状态压缩DP)
    HDU 5013 City Tour
    BZOJ 3672 [Noi2014]购票 (熟练剖分+凸壳维护)
    BZOJ 1488: [HNOI2009]图的同构 polay
    BZOJ 1565 植物大战僵尸(最大权闭合图)
    iOS加载程序视图的方式
    内存管理2(主讲MRR)
    内存管理1
    排序算法之希尔排序
  • 原文地址:https://www.cnblogs.com/ZJOE80/p/14452416.html
Copyright © 2011-2022 走看看