简体   繁体   中英

mysql select count of records from a string which have exact substring

I have the five records which is like below. I need to fetch the data which have 'rock'. So I need the output like this, the output should display the count of 'rock', so according to the above database the output count should be "3" ie, rec 1, rec 3 & rec 5". So the count should not take "rec 2 & rec 4".

rec1: [u'armenian rock', u' armenian', u' singer-songwriter', u' rock'] 
rec2: [u'punk', u' armenian rock', u' new wave', u' italian']
rec3: [u'rock']
rec4: [u'japanese', u' okuda tamio related', u" rock'n'roll", u' roots rock']
rec5: [u'test rock', u' armenian', u' singer-songwriter', u" rock"]

Try the string function

INSTR(str,substr)

In your query.

Something like this:

SELECT COUNT(*) FROM yourTable WHERE INSTR(yourTable.tags, 'rock') > 0;

Another option could be the use of

LOCATE(substr,str), LOCATE(substr,str,pos)

Please have a look into the mysql documentation:

http://dev.mysql.com/doc/refman/5.1/en/string-functions.html

SELECT (LENGTH(tags) - LENGTH(REPLACE(tags, 'rock', ''))) / LENGTH('rock') AS count FROM your_table

Try this. Yes, looks bloated but as far as i know there is no any other possible solution.

SELECT SUM((LENGTH(tags) - LENGTH(REPLACE(tags, 'u\' rock', ''))) / LENGTH('u\' rock'))as counting 
FROM tableName

FIDDLE

You can use this:

SELECT COUNT(*) FROM Table1 WHERE INSTR(Table1.tags, '\' rock') > 0;

fiddle

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