简体   繁体   English

MYSQL计算SOME值作为表的字段中的值存在的次数

[英]MYSQL count how many times SOME value is exist as value in a field of table

MYSQL Check If some value is exist as value in a field of table MYSQL检查如果某个值作为表的字段中的值存在

I have table A with field : 我有表A字段:
id name value id名称值
1 item1 822 1项1 822
2 item2 658 2项2 658
3 item3 321 3项3 321

I'm trying to figure out this : 我想弄清楚这个:
I want to count how many times values is exist in a field 我想计算一个字段中存在多少次值

example : 例如:
If I'm searching 2 and 8, then 如果我正在搜索2和8,那么

The Result is : The count is 3 for row id 1 ( because it's has two 2 and one 8 ) 结果是:行id 1的计数为3(因为它有两个2和一个8)

And the count is 1 for row id 2 ( because it's has one 8 number ) 对于行ID 2,计数为1(因为它有一个8位数)

And the count is 1 for row id 3 ( because it's has one 2 number ) 行id 3的计数为1(因为它有一个2号)

select id, case when value like '%2%' then 1 else 0 end +
               case when value like '%8%' then 1 else 0 end
from tablename

You can do this with replace() and length() (or char_length() ): 您可以使用replace()length() (或char_length() )执行此操作:

select (length(value) - length(replace(replace(value, '2', ''), '8', ''))) as num_occurrences
from t;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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