Need a row count after SELECT statement: what's the optimal SQL approach?

后端 未结 10 1071
悲哀的现实
悲哀的现实 2020-12-05 02:19

I\'m trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two app

10条回答
  •  温柔的废话
    2020-12-05 02:42

    Approach 2 will always return a count that matches your result set.

    I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.

    SELECT 
      mt.my_row,
     (SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt
    FROM my_table mt
    WHERE mt.foo = 'bar';
    

提交回复
热议问题