简体   繁体   English

mysql查询count()限制为8

[英]mysql query count() limit to 8

Is there away to limit the result count on this query (attached). 有没有办法限制此查询的结果计数(附加)。 On attached screen shot there is a result of ten counts i'm wondering if there's a way to limit or restrict the count into 8 regardless how is the result per mobile number? 在所附的屏幕截图中,有十个计数的结果,我想知道是否有一种方法可以将计数限制或限制为8,而无论每个手机号码的结果如何? thanks 谢谢 查询数

UPDATE: 更新:

Need to update my question: I need to get the latest 8 per mobile number on this query. 需要更新我的问题:在此查询中,我需要获取每个手机号码的最新8。 see attached: 见附件:

in the results; 结果中 a mobile number 7824 has a 10 records. 手机号码7824有10条记录。 My goal is to get the total votes per each code but limited to 8 votes per mobile number. 我的目标是获得每个代码的总票数,但每个手机号码限制为8票。

在此处输入图片说明

Instead of: 代替:

select x.* from 

do: 做:

select case when x.count > 8 then 8 else x.count end as count, 
       x.mobile_number, 
       x.code

使用以下条件:

select if(count(a.id)>8,8,count(a.id)) as count

No need of sub-query you can get by main query as per below- 不需要子查询,您可以按以下方式通过主查询获得-

SELECT IF(COUNT(a.id) > 8, 8, COUNT(a.id)) AS 'count', a.mobile_number, a.shortcode AS 'code'
FROM tbl_votes AS a 
INNER JOIN tbl_members AS b ON b.mobile_number = a.mobile_number 
WHERE a.possition_id = 3 
GROUP BY a.mobile_number;

Updated Answer as per Updated Query: 根据更新的查询更新答案:

SELECT t.id, t.mobile_number, t.shortcode AS 'code' 
FROM (SELECT t.id, t.mobile_number, t.shortcode,
               CASE 
                 WHEN @category != t.mobile_number THEN @rownum := 1 
                 ELSE @rownum := @rownum + 1 
               END AS rank,
               @category := t.mobile_number AS var_category
          FROM tbl_votes t
          JOIN tbl_members AS b ON b.mobile_number = t.mobile_number 
          JOIN (SELECT @rownum := NULL, @category := '') r     
      ORDER BY t.mobile_number,t.id DESC) X
      WHERE x.rank<=8;

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

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