I have this table:
CREATE TABLE `mytable` (
`id` int(11) NOT NULL,
`value` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
With this data:
id, value
--------------------
'1', '__cccccccc; Myword'
'2', '__ddddddd; Myword'
'3', 'OOO; myword; anotherword'
And this query:
SELECT `mytable`.`value`
, LENGTH(`mytable`.`value`) 'string length'
, LENGTH(REPLACE(LOWER(`mytable`.`value`),'; myword','')) 'after replace'
, LENGTH(`mytable`.`value`) - LENGTH(REPLACE(`mytable`.`value`,'; myword','')) 'after sub'
, LENGTH(`mytable`.`value`) - LENGTH(REPLACE(`mytable`.`value`,'; myword',''))/8 'after divide'
FROM mytable
WHERE LOWER(`mytable`.`value`) LIKE '%; myword%'
OR LOWER(`mytable`.`value`) LIKE '%; myword';
And this result:
# value, string length, after replace, after sub, after divide
'__cccccccc; Myword', '18', '10', '8', '16.7500'
'__ddddddd; Myword', '17', '9', '8', '15.8750'
'OOO; myword; anotherword', '24', '16', '8', '22.0000'
The insert statement:
INSERT INTO `test`.`mytable`
(`id`,
`value`)
VALUES
('1','__cccccccc; Myword'),
('2','__ddddddd; Myword'),
('3','OOO; myword; anotherword');
The problem is the last column result is incorrect. For example, the last column in the first record should be 8/8 which is 1. Why am I getting these results? How to correct them plz with the minimal changes?
Note: I need to convert the strings to lowercase using LOWER because replace is case sensitive and my values are case sensitive (I need to capture any occurrence of the keyword ; myword
whether it contains capital or small letters, I do not care.
EDIT:
The query aims to count the number of times the string ; myword
appeared. So I count the length of the field, and subtract it from the length of the field after replacing the keyword I want to count with nothing ''
. Then divide the result with the number of characters in the keyword string (8 in my case).