简体   繁体   中英

count() Pagination with one-to-many Relation and WHERE IN

The main Problem is the 'WHERE IN' on a Relation part, which multiply the found Rows.
For example where I added GROUP_CONCAT for a better view whats going on:

SELECT COUNT(*),
GROUP_CONCAT(sections.name SEPARATOR '; ')
FROM users
LEFT JOIN users_sections ON (users.id = users_sections.user_id) 
LEFT JOIN sections ON (users_sections.section_id = sections.id)
GROUP BY users.id

Finds:
'2', 'Registered; admins'
'3', 'Registered; admins; dudes'
'1', 'Registered'

There are found 3 Rows, what is correct, but the Result is useless.
Now add the WHERE IN part:

SELECT COUNT(*),
GROUP_CONCAT(sections.name SEPARATOR '; ')
FROM users
LEFT JOIN users_sections ON (users.id = users_sections.user_id) 
LEFT JOIN sections ON (users_sections.section_id = sections.id)
WHERE sections.id IN (2,3)
GROUP BY users.id

Finds:
'2', 'Registered; admins'
'2', 'Registered; admins'
'1', 'Registered'

Even correct but useless. I need one single '3' as COUNT result.
Ok then, lets remove the GROUP_CONCAT and ...pray

SELECT COUNT(*)
FROM users
LEFT JOIN users_sections ON (users.id = users_sections.user_id) 
LEFT JOIN sections ON (users_sections.section_id = sections.id)
WHERE sections.id IN (2,3)
GROUP BY users.id

Find:
'2'
'2'
'1'

The same as before. Lets try this:

SELECT COUNT(*) > 0
...

Find:
'1'
'1'
'1'

Hey, that looks good! Lets try that (hopefully finally):

SELECT SUM(COUNT(*) > 0)
...

Find:
Invalid use of group function

So sad...
How can I get the Count for that, or is it impossible?

What you want to do (if i read correctly) is counting distinct user ids where a certain condition applies. I couldn't get the real question out of it, but I think you need it in the line of:

SELECT 
    COUNT( DISTINCT users.id)
FROM
    users
    LEFT JOIN users_sections ON (users.id = users_sections.user_id) 
    LEFT JOIN sections ON (users_sections.section_id = sections.id)
WHERE 
    sections.id IN (2,3)

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