Should I COUNT(*) or not?

前端 未结 14 1625
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 15:49

I know it\'s generally a bad idea to do queries like this:

SELECT * FROM `group_relations`

But when I just want the count, should I go for this

14条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 16:15

    I know it's generally a bad idea to do queries like this:

    SELECT * FROM `group_relations`
    

    But when I just want the count, should I go for this query since that allows the table to change but still yields the same results.

    SELECT COUNT(*) FROM `group_relations`
    

    As your question implies, the reason SELECT * is ill-advised is that changes to the table could require changes in your code. That doesn't apply to COUNT(*). It's pretty rare to want the specialized behavior that SELECT COUNT('group_id') gives you - typically you want to know the number of records. That's what COUNT(*) is for, so use it.

提交回复
热议问题