How to get the number of rows of the selected result from sqlite3?

前端 未结 8 520
情话喂你
情话喂你 2020-12-01 12:00

I want to get the number of selected rows as well as the selected data. At the present I have to use two sql statements:

one is

select * from XXX w         


        
8条回答
  •  被撕碎了的回忆
    2020-12-01 12:22

    For those who are still looking for another method, the more elegant one I found to get the total of row was to use a CTE. this ensure that the count is only calculated once :

    WITH cnt(total) as (SELECT COUNT(*) from xxx) select * from xxx,cnt
    

    the only drawback is if a WHERE clause is needed, it should be applied in both main query and CTE query.

    In the first comment, Alttag said that there is no issue to run 2 queries. I don't agree with that unless both are part of a unique transaction. If not, the source table can be altered between the 2 queries by any INSERT or DELETE from another thread/process. In such case, the count value might be wrong.

提交回复
热议问题