MAX()在COUNT()子查询上返回多行

时间:2011-07-12 11:50:30

标签: mysql count

我有一个查询,它获取选择记录中返回的行数,我的查询如下所示:

SELECT rec.record_id,
       rec.record_title,
       usr.user_id,
       usr.username,
       (
           SELECT COUNT(DISTINCT rec.record_id)
           FROM records rec
           WHERE rec.record_title LIKE '%random%'
           GROUP BY rec.record_id
       ) AS total_records
FROM 
(
    records rec

    INNER JOIN members usr
)
WHERE rec.record_title LIKE '%random%'
GROUP BY rec.record_id
LIMIT 0, 25

我需要能够使用包含total_records时找到的最大数量返回GROUP BY子查询中的记录数,并返回多条记录,我只需要一条记录,应该是在子查询中找到的记录数。

如何通过查找找到的最大数量或添加多个记录来查找子查询中的总记录,以便找到大量记录。

2 个答案:

答案 0 :(得分:1)

我想我需要澄清一下......最大数量是什么? “使用找到的最大数量”

我通常不愿意将子查询放在select语句中。我可能会像这样重组你的(很确定它是一样的)看看这样想是否有帮助?

SELECT rec.record_id, rec.record_title, usr.user_id, usr.username
FROM ( records rec

INNER JOIN members usr
INNER JOIN  (
       SELECT COUNT(DISTINCT rec.record_id), rec.record_id as record_id
       FROM records rec
       WHERE rec.record_title LIKE '%random%'
       GROUP BY rec.record_id
   ) AS total_records on rec.record_id = total_records.record_id

) 在哪里rec.record_title LIKE'%random%' GROUP BY rec.record_id 限制0,25

答案 1 :(得分:-1)

也许这就是你想要的?如果没有,请澄清你的问题,我会再试一次。

SELECT rec.record_id,
    rec.record_title,
    usr.user_id,
    usr.username,
    (
            SELECT MAX(count) FROM (
                SELECT COUNT(DISTINCT rec.record_id) AS count
                FROM records rec
                WHERE rec.record_title LIKE '%random%'
                GROUP BY rec.record_id
            ) AS x
    ) AS total_records
FROM
(
    records rec

    INNER JOIN members usr
)
WHERE rec.record_title LIKE '%random%'
GROUP BY rec.record_id
LIMIT 0, 25