用于从逗号分隔列中检索值的SQL查询

时间:2012-01-07 13:24:13

标签: php mysql sql zend-framework select

  

可能重复:
  Split string in SQL
  Searching a column with comma seperated values

在我的 PHP 项目中,我遇到了编写SQL的问题:

我有一个表“顾问”,字段 类别 ,其值如下:

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ id |  consultant_name  | categories                           +
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+  1 |  AOAOAO           | health,insurance,programming,        +
+  2 |  BOBOBO           | health,gaming,windows,mobile,        +
+  3 |  CCCCCC           | insurance,windows,                   + 
+  4 |  DDDDDD           | mobile,                              +
+  . |  ......           | ............                         +
+  . |  ......           | ............                         +
+  . |  ......           | ............                         +
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

我有一个数组,其中包含顾问可以注册的所有类别

$arrayOfCategories =  $array("health","insurance","programming",
                             "sports","gaming","windows","apple",
                             "mobile","astrology");

我想要的是一个 SQL查询,它应该给我一个输出,如:

+++++++++++++++++++++++++++++++
+ category      | occurrence  +    
+++++++++++++++++++++++++++++++
+ health        | 2           +
+ insurance     | 2           +
+ programming   | 1           +
+ sports        | 0           +
+ gaming        | 1           +
+ windows       | 2           +
+ apple         | 0           +
+ mobile        | 2           +
+ astrology     | 0           +
+++++++++++++++++++++++++++++++

任何形式的帮助都将受到赞赏......

提前致谢...

3 个答案:

答案 0 :(得分:1)

这是一个糟糕的数据库设计。如果我坚持使用它,我不会尝试使用SQL来获取事件,但我的应用程序。

创建一个名为$ occurence的新数组,它将包含每个单词和计数的索引。 选择每一行并在逗号上拆分类别的内容。循环遍历此结果数组并为每个单词递增。

我在PHP中有点生疏,所以这是我在Perl中的建议:

my %occurrence;

while ( my ($categories) = $sth->fetchrow_array() ){

   my @cats = split(',', $categories);

   foreach my $c (@cats){
      $occurrence{$c}++;
   }

}

这种方式的一个好处是,您可以找到任何错误的类别,并且在添加新类别时不必更新SQL。

答案 1 :(得分:1)

糟糕的数据库设计但有趣的问题,这是我的方法(php代码):

$arrayOfCategories =  $array("health","insurance","programming",
                             "sports","gaming","windows","apple",
                             "mobile","astrology");

 $count = count($arrayOfCategories);
 $query = "";
 for($i = 0; $i < $count; $i++)
 {
   $value = $arrayOfCategories[$i];
   $query += "SELECT '$value' AS category,
                 COUNT(*) AS occurrence
                 FROM consultants
                 WHERE FIND_IN_SET('$value', categories)";
    if($i < $count -1) {
    $query += " UNION "
    }


 }

生成的查询的结果应该能够准确地提供您想要的内容。通常从糟糕的设计中提出有趣的问题......:)

答案 2 :(得分:0)

如果你有一个包含类别的表,你可以这样做:

SELECT cat.name, COUNT(*) 
FROM categories cat JOIN consultants con ON con.categories LIKE '%'+cat.name+'%'

尽管如此,我认为这很尴尬,你应该考虑规范化db方案,以便有一个顾问类别关系的映射表