[英]Counting Number of Rows containing each string in a different column in MySql
我有以下问题:我有一个名为 FOOD 的表,其中有一列“NAME”包含食物名称,例如“Rice”、“White Rice”、“Milk”、“Soy Milk”等。
我需要过滤掉 NAME 只包含一个单词的行,然后计算这些单个单词作为食物名称的一部分出现在 NAME 列中的行数。
例如,如果 NAME 列是:“Rice”、“White Rice”、“Milk”、“Soy Milk”、“Brown Rice”,那么结果应该是 Rice - count is 3 和 Milk - count is 2。
我知道如何获取 NAME 列中包含单个单词的值:
SELECT NAME AS lones FROM FOOD WHERE NAME NOT LIKE '% %' GROUP BY lones
我如何从这里继续?
谢谢
试试这个查询。 我将food
与一个由单字食物组成的临时表连接起来(我通过选择没有空格的名称来创建)。
JOIN 条件是单个单词 food 出现在连接的 food 表的 name 列中。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.