My problem is (maybe) a bit complex, I try to write it down comprehensible. I have a Class in PHP which generates a MySQL query depending on several circumstances and parameters (then displays the query result in a dinamyc table). For example here are the tables and an example query:
It is simple, There are users, and each user can have one or more profiles assigned. For exmaple we have only one user and he has two profiles:
[USER]
userid login password status reg_date
------ ------- ---------- ------ -------------------
1 JohnDoe hd98349... 0 2014-01-09 16:00:55
[PROFILE]
profile_id profile_name
---------- ------------
1 admin
2 root
3 user
[USER_PROFILE]
relation_id user profile
----------- ----- -------
1 1 1
2 1 2
My PHP code generates a query that looks like this for example:
SELECT
userid AS 'User id',
login AS 'User name',
GROUP_CONCAT(profile_name SEPARATOR ', ') AS 'Profile(s)',
`status`
FROM `user` LEFT JOIN user_profile ON `user`.userid = user_profile.`user`
LEFT JOIN `profile` ON user_profile.`profile` = `profile`.profile_id
WHERE
status IN (0, 1)
ORDER BY reg_date ASC
LIMIT 0 ,10
And the result for this query is:
[RESULT]
User id User name Profile(s) status
------- --------- ---------- ------
1 JohnDoe root, admin 0
When I want to use filters on a column that is originated from a subquery or a complex expression (like the GROUP_CONCAT(profile_name SEPARATOR ', ')
) I get false result:
SELECT COUNT(*) AS 'all_rows'
FROM `user` LEFT JOIN user_profile ON `user`.userid = user_profile.`user`
LEFT JOIN `profile` ON user_profile.`profile` = `profile`.profile_id WHERE status IN (0, 1)
HAVING GROUP_CONCAT(profile_name SEPARATOR ', ') LIKE '%root%'
This will result in: 'all_rows' => 2. This is because the GROUP_CONCAT in the HAVING won't group, but If I put it in the SELECT like: SELECT COUNT(GROUP_CONCAT(profile_name SEPARATOR ', ')) I get an error
So the question is how could I get the number of all rows using a GROUP_CONCAT in a filter (WHERE / HAVING) expression?
EDIT: Before I run the main query I need to know how many record rows would it result, without the LIMIT restriction. I use this to calculate the start row value for the LIMIT for pagination purposes.