【问题标题】:MySql Comma Separated Values , Fetch Using Where ClauseMySql 逗号分隔值,使用 Where 子句获取
【发布时间】:2014-11-13 14:53:12
【问题描述】:

我必须获取 table 的列,其中一列值用分隔逗号分隔,这是我的表结构

id  | name | categoryID
 1    a       1,2,4
 2    b       333 , 1 , 5 , 54
 3    c       1114414 , 2 , 3, 4, 5, 6 ,7
 4    d       2 , 4 , 5, 333, 7 , 8

Here is my query

Select * from tableA where find_in_set ('categoryID' , '1,7,8,333');

但上面的查询不起作用,它返回空行。

【问题讨论】:

  • 您正在搜索所有这 4 个值?那不是find_in_sets 的工作
  • 为什么你的模式是一种奇怪的方式?

标签: php mysql


【解决方案1】:
Select * from tableA where find_in_set (categoryID , '1,7,8,333')

如果您为 categoryID 传递值 1,“find_in_set”将正确返回该值。 但是你试图通过 (1,2,4), (333 , 1 , 5 , 54)。因此它返回错误的值。

【讨论】:

    【解决方案2】:

    第 1 步:

    我建议您更改架构。一个名称映射到多个类别

    id,name,categoryId
    1  a     1
    2  a     2
    3  a     4
    4  b     1
    5  b     5
    

    第 2 步:

    查找以下类别的所有名称

    Select distinct name,id,category_id from tableA where categoryId IN (1,7,8,333);
    

    【讨论】:

      【解决方案3】:

      您必须在 find_in_set 错误的地方使用 OR。 用作

      Select * from tableA where find_in_set ('1',categoryID) OR find_in_set ('7',categoryID);
      

      不要在单引号内引用 categoryID。

      【讨论】:

        【解决方案4】:

        您对 find_in_set 函数的使用不正确。 以下内容可能很有用,因为它描述了如何正确使用 find_in_set 函数。

        给你:find_in_set

        所以,用它来查找字符串在逗号分隔列表中的位置,像这样(注意它不区分大小写):

        select find_in_set('Z', 'a,b,z,0');
        

        // 将产生:3

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-08-23
          • 1970-01-01
          • 2012-05-15
          • 2018-04-08
          • 1970-01-01
          • 1970-01-01
          • 2020-12-09
          • 1970-01-01
          相关资源
          最近更新 更多