简体   繁体   English

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

[英]Counting Number of Rows containing each string in a different column in MySql

I have the following problem: I have a table called FOOD with a column "NAME" containing name of foods, such as "Rice", "White Rice" , "Milk", "Soy Milk" etc.我有以下问题:我有一个名为 FOOD 的表,其中有一列“NAME”包含食物名称,例如“Rice”、“White Rice”、“Milk”、“Soy Milk”等。

I need to filter out the rows which have a NAME containing only a single word, and then count in how many rows each of these single words appears in the NAME column as a part of a name of a food.我需要过滤掉 NAME 只包含一个单词的行,然后计算这些单个单词作为食物名称的一部分出现在 NAME 列中的行数。

For example if the NAME column is: "Rice", "White Rice" , "Milk", "Soy Milk", "Brown Rice", Then the result should be Rice - count is 3 and Milk - count is 2.例如,如果 NAME 列是:“Rice”、“White Rice”、“Milk”、“Soy Milk”、“Brown Rice”,那么结果应该是 Rice - count is 3 和 Milk - count is 2。

I know how to get the values in NAME column which contain a single word:我知道如何获取 NAME 列中包含单个单词的值:

SELECT NAME AS lones FROM FOOD WHERE NAME NOT LIKE '% %' GROUP BY lones

How do I continue from here?我如何从这里继续?

Thanks谢谢

Try this query.试试这个查询。 I JOIN food against a temp table consisting of single-word foods (which I create by selecting names without space in them).我将food与一个由单字食物组成的临时表连接起来(我通过选择没有空格的名称来创建)。

The JOIN condition is that the single-word food is present in the joined food table's name column. JOIN 条件是单个单词 food 出现在连接的 food 表的 name 列中。

POSITION() works like indexOf() function in other languages. POSITION() 的工作方式类似于其他语言中的 indexOf() 函数。 It returns 0 if the search string is not found in the source string.如果在源字符串中找不到搜索字符串,则返回 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM