As per official documentation, FIND_IN_SET returns the position of the first occurrence of string available from a comma-separated list. But I want to get the count of available string in a comma-separated list.
For example :
SELECT id, name, FIND_IN_SET(id, '1,1,2,3,4,4,5,6,7,7,7') as num FROM users;
It returns the following result
+----+---------------+
| id | name | num |
+----+---------------+
| 1 | Jack | 1 |
| 2 | Alex | 3 |
| 3 | John | 4 |
| 4 | Brett | 5 |
| 5 | Keith | 7 |
| 6 | Richard | 8 |
| 7 | Kent | 9 |
+----+---------------+
SQL Fiddle: http://sqlfiddle.com/#!9/9eeacb/2
But I want the count of ids which matches the id of the table. So, the expected output should be like below.
SELECT id, name, SOME_FUNCTION(id, '1,1,2,3,4,4,5,6,7,7,7') as num FROM users;
+----+---------------+
| id | name | num |
+----+---------------+
| 1 | Jack | 2 |
| 2 | Alex | 1 |
| 3 | John | 1 |
| 4 | Brett | 2 |
| 5 | Keith | 1 |
| 6 | Richard | 1 |
| 7 | Kent | 3 |
+----+---------------+
The best answer is to move away from the CSV paradigm, and instead get the set of id
s to match into its own table:
CREATE TABLE ids (id int);
INSERT INTO ids (id)
VALUES (1),(1),(2),(3),(4),(4),(5),(6),(7),(7),(7);
Then use the following simple query:
SELECT
u.id,
u.name,
COUNT(i.id) AS num
FROM users u
LEFT JOIN ids i
ON u.id = i.id
GROUP BY
u.id,
u.name;
Use string functions tricks:
set @s = '1,1,2,3,4,4,5,6,7,7,7';
select id, name,
ceiling((length(@s) - length(trim(both ',' from replace(
replace(concat(',', replace(@s, ',', ',,'), ','), concat(',', id, ',' ), ''),
',,', ','
)))) / (length(id) + 1)) as num
from users
See the demo (with other possible cases).
Results:
id | name | num
1 | Jack | 2
2 | Alex | 1
3 | John | 1
4 | Brett | 2
5 | Keith | 1
6 | Richard | 1
7 | Kent | 3
You are passing in the comparison values as a string. You can do some string tricks to count the number of values within the string and then add that up:
SELECT u.id, u.name,
COUNT(*),
SUM( (LENGTH(REPLACE(CONCAT(',', ids, ','), u.id, CONCAT(u.id, 'X'))) -
LENGTH(CONCAT(',', ids, ','))
)
)
FROM users u CROSS JOIN
(SELECT '1,1,2,3,4,4,5,6,7,7,7' as ids) x
WHERE FIND_IN_SET(u.id, x.ids) > 0
GROUP BY u.id, u.name;
Note: I created the subquery x
as a convenience, so I can refer to ids
. You can pass in the value as a parameter instead:
SELECT u.id, u.name,
COUNT(*),
SUM( (LENGTH(REPLACE(CONCAT(',', ?, ','), u.id, CONCAT(u.id, 'X'))) -
LENGTH(CONCAT(',', ?, ','))
)
)
FROM users u
WHERE FIND_IN_SET(u.id, ?) > 0
GROUP BY u.id, u.name;
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.