1. 程式人生 > >mysql獲取group by的總記錄行數方法 親測

mysql獲取group by的總記錄行數方法 親測

mysql獲取group by的總記錄行數方法
原方法:
1. group by 後分組的前十條,在頁面展示:size=20

SELECT column_name as count FROM mac_activity ma left join mac_ticket_channel mtc on ma.id=mtc.activity_id where ma.delete_flag=0 and mtc.delete_flag=0 <include refid="findActivityListByApply"/>group by mtc.activity_id,mtc.issue_channel_cd order by ma.create_time desc <if test="pageBean!=null and pageBean.offset !=null "> limit #{pageBean.offset},#{pageBean.size} </if>;

2. group by的總記錄數,也需要在頁面顯示:

select count(*) from (SELECT count(distinct ma.id) as count FROM mac_activity ma left join mac_ticket_channel mtc on ma.id=mtc.activity_id group by mtc.activity_id) T;

原方法已親測,group by mtc.activity_id,mtc.issue_channel_cd現查詢當前頁條數的group by有2個分組條件,所以分頁查詢時每頁的條數=每頁的條數*2,同理如果是3個分組條件,每頁的條數=每頁的條數*3.

查詢總條數時通過子查詢完成,子查詢中查id時加上distinct去掉重複的,子查詢分組時只用1個條件用活動activity_id即可不需要2個條件,加上issue_channel_cd將線上和線下分別都作為總數加到一塊兒了,如果加()後,記得加臨時表名T,否則報錯every derived table must have its own alias,如果不給臨時表加()時,報語法錯誤。

新方法:
mysql使用關鍵字SQL_CALC_FOUND_ROWS獲取group by的總記錄行數

1.SELECT SQL_CALC_FOUND_ROWS column_id,count(*) as count FROM my_table group by column_id limit 10;
2.select FOUND_ROWS();

 

SQL_CALC_FOUND_ROWS所在的查詢語句中,記錄查詢到的總條數(與limit無關);
select FOUND_ROWS();即返回查詢語句中找到的總記錄數;