简体   繁体   English

count()具有一对多关系和WHERE IN的分页

[英]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. 主要问题是关系部分的“WHERE IN”,它将找到的行数相乘。
For example where I added GROUP_CONCAT for a better view whats going on: 例如,我添加了GROUP_CONCAT以获得更好的视图:

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. 有3行,这是正确的,但结果是没用的。
Now add the WHERE IN part: 现在添加WHERE IN部分:

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. 我需要一个单独的'3'作为COUNT结果。
Ok then, lets remove the GROUP_CONCAT and ...pray 好吧,让我们删除GROUP_CONCAT并祈祷

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. 您想要做什么(如果我正确读取)是计算特定条件适用的不同用户ID。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM