简体   繁体   中英

Count the number of occurrences of a string across multiple attributes in MySQL Database How

How can I count the number of occurrences of a string across multiple attributes (in my current case, I have 5 attributes) of a table in a MySQL database? Can I do so using MySQL quer(y/ies)?

The attributes may have NULL values, if that means anything while counting.

Also, I am using PHP on the client-side which I could use if MySQL wouldn't be the better way to find this count, though I want to know how this can be done with MySQL.

I saw this post , and it's similar to what I want to do, but this solution only works for counting strings over one attribute/column. I need to count the total occurrences of each string over all (eg: 5) of my attributes/columns.

declare @string nvarchar(255) = "string" --String to search for

select COUNT(t1.attr_1) + COUNT(t2.attr_2) + COUNT(t3.attr_3) + COUNT(t4.attr_4) + COUNT(t5.attr_5)
from Table_name t
join Table_name t1 on t1.id = t.id
join Table_name t2 on t2.id = t.id
join Table_name t3 on t3.id = t.id
join Table_name t4 on t4.id = t.id
join Table_name t5 on t5.id = t.id
where t1.attr_1 = @string
and t2.attr_2 = @string
and t2.attr_3 = @string
and t2.attr_4 = @string
and t2.attr_5 = @string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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