简体   繁体   中英

How to count how many times a string appears in a field in mySQL separated by comma?

My mySQL is like this, an id , and a texts that have may phrases and some identical as below:

id      texts
2       abc,fd4g,oigdu,abc,abc
3       ccc,fff,fff,ccc,iop

My question is how can I show using PHP/mySQL

  1. per id

2 - abc - 3 times

2 - fd4g - 1 times

2 - oigdu - 1 times

3 - ccc - 2 times

3 - fff - 2 times

3 -iop - 1 times

  1. or searching via the text

    abc - 2 times - 2

    fd4g - 1 times - 2

    oigdu - 1 times - 2

    ccc - 2 times - 3

    fff - 2 times - 3

    iop - 1 times - 3

-

If my mySQL structure was :

id      texts
2       abc
2      fd4g
2      oigdu
2      abc
2      abc
3       ccc
3      fff
3      fff
3      ccc
3      iop

would this be easier?

The second structure would be easier. But you shouldn't name your first column id because the id -field usually has unique key values, that means only auto-incrementing values. You have multiple times the same number, so you it's obviously not unique but something different.

With the other query you could run

SELECT id, texts, COUNT(*) FROM tbl group by id, texts

and your result would be

2  |  abc  |  3
2  | fd4g  |  1

and so on.

您可以通过执行以下代码来获得相同值的计数

select id, texts, count(id) from table group by texts

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