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

时间:2013-12-13 07:53:47

标签: php mysql join orm pagination

主要问题是关系部分的'WHERE IN',它将找到的行数相乘 例如,我添加了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'

有3行,这是正确的,但结果没用 现在添加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'

即使是正确但无用的。我需要一个单独的'3'作为COUNT个结果 好吧,让我们删除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'

和以前一样。让我们试试这个:

SELECT COUNT(*) > 0
...

Find:
'1'
'1'
'1'
嘿,看起来不错!让我们试试(希望最终):

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

Find:
Invalid use of group function

太伤心了...... 我怎么能得到伯爵,或者不可能?

1 个答案:

答案 0 :(得分:2)

您想要做什么(如果我正确阅读)是计算特定条件适用的不同用户ID。我无法从中得到真正的问题,但我认为你需要它:

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)