【问题标题】:How can I Select the data from the database using Comma如何使用逗号从数据库中选择数据
【发布时间】:2014-01-14 01:25:52
【问题描述】:

这是我的需要库存表。这里我要根据NeedGroupIds选择Id、Name。这很好,但这里的问题是,如果我只传递12,15,那么它会给出输出。但是,如果我只是通过 12 意味着我需要得到两行的输出,即 Markersintel 但失败了。

如何根据逗号选择数据。

【问题讨论】:

  • 尝试复制粘贴,为什么要在 sqlfiddle 中作为图像或发布,并用正确的要求格式化问题!!
  • @ChandruGayathri:检查我的答案。

标签: mysql sql-server sql-server-2008


【解决方案1】:

您可以使用如下查询:

SELECT * FROM `tableName` WHERE  fieldName REGEXP '^9,|,9$|,9,' OR fieldName =9

更多信息可以查看文档:http://dev.mysql.com/doc/refman/5.1/en/regexp.html

【讨论】:

    【解决方案2】:

    MySQL:使用FIND_IN_SET(str,strlist)

    SELECT col1, col2, ... FROM my_table
      WHERE FIND_IN_SET(value_to_find, NeedGroupIds);  
    /** if found, find_in_set should result in a number > zero **/
    

    示例 1

    SELECT FIND_IN_SET( 6, ',5,6,7,' ); -- results 3  
    SELECT FIND_IN_SET( '7', ',5,6,7,' ); -- results 4  
    SELECT FIND_IN_SET( '8', ',5,6,7,' ); -- results 0  
    

    MsSQL:使用LIKE (Transact-SQL)

    /** For non-mysql databases, an alternate to FIND_IN_SET **/  
    SELECT col1, col2, ... FROM my_table
      WHERE ',' + NeedGroupIds + ',' LIKE '%,12,%';  
    

    示例 2

    /** this should result `Markers` **/  
    SELECT col1, col2, ... FROM my_table  
      WHERE ',' + NeedGroupIds + ',' LIKE '%,12,15,%';  
    
    /** this should result `Markers` and `intel` **/  
    SELECT col1, col2, ... FROM my_table  
      WHERE ',' + NeedGroupIds + ',' LIKE '%,12,%';  
    
    /** this should result `Pen` and `cello` **/  
    SELECT col1, col2, ... FROM my_table  
      WHERE ',' + NeedGroupIds + ',' LIKE '%,2,%';  
    

    参考Alternate to FIND_IN_SET for non-MySQL databases

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多