SQL count(*) and distinct

前端 未结 9 1985
野趣味
野趣味 2021-02-12 11:25

Why can\'t we use count(distinct *) in SQL? As in to count all distinct rows?

9条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-12 12:07

    select count(*) from (select distinct * from MyTable) as T
    

    Although I strongly suggest that you re-think any queries that use DISTINCT. In a large percentage of cases, GROUP BY is more appropriate (and faster).

    EDIT: Having read the question comments, I should point out that you should never ask the DBMS to do more work than actually needs doing to get a result. If you know in advance that there will not be any duplicated rows in a table, then don't use DISTINCT.

提交回复
热议问题