计算包含MySql中不同列中每个字符串的行数

时间:2017-10-29 09:00:58

标签: mysql sql

我有以下问题: 我有一个名为FOOD的表,其中包含“NAME”列,其中包含“Rice”,“White Rice”,“Milk”,“Soy Milk”等食品名称。

我需要过滤掉只包含一个单词的NAME的行,然后计算每个单词在NAME列中显示的行数,作为食物名称的一部分。

例如,如果NAME列是:“Rice”,“White Rice”,“Milk”,“Soy Milk”,“糙米”,则结果应为Rice - 计数为3,Milk计数为2

我知道如何获取NAME列中包含单个单词的值:

  public function rules()
{
    $cid = \Route::input('id');
    $isEdit = isset($cid) ? true : false;
    $rules = array(
        'name' => 'required|string|Max:50',
        'father_name' => 'required|string|Max:50',
        'class' => 'required|string|Max:50',
        'date' => 'required|date|Max:50',
        'teacher_name' => 'required|string|Max:50',
        'remarks' => 'required',
        'roll_no' => 'required',
    );
    return $rules;
}

我如何从这里继续?

由于

1 个答案:

答案 0 :(得分:1)

尝试此查询。我加入food对一个由单字食物组成的临时表(我通过选择没有空格的名字来创建)。

JOIN条件是单字食物出现在连接食物表的名称栏中。

POSITION()的工作方式与其他语言中的indexOf()函数类似。如果在源字符串中找不到搜索字符串,则返回0。

select single_word_foods.name, count(*) 
from food INNER JOIN 
(select distinct name from food where position(' ' in name) = 0) as single_word_foods
on POSITION(single_word_foods.name in food.name) > 0
group by single_word_foods.name;
相关问题