2009-05-20 107 views
8

我想統計表中的記錄總數和匹配特定條件的總記錄數。我可以做兩個單獨的查詢這些:兩個SQL COUNT()查詢?

SELECT COUNT(*) AS TotalCount FROM MyTable; 
SELECT COUNT(*) AS QualifiedCount FROM MyTable 
    {possible JOIN(s) as well e.g. JOIN MyOtherTable mot ON MyTable.id=mot.id} 
    WHERE {conditions}; 

有沒有辦法將這些組合成一個查詢,以便我在一行中獲得兩個字段?

SELECT {something} AS TotalCount, 
    {something else} AS QualifiedCount 
    FROM MyTable {possible JOIN(s)} WHERE {some conditions} 

如果沒有,我可以發出兩個查詢和包裹他們在一個交易所以它們是一致的,但我希望有一個做到這一點。

編輯:我最關心的是原子性;如果有兩個子SELECT語句需要,那麼只要有一個INSERT來自某個地方,它就不會使這兩個響應不一致。

編輯2:CASE的答案很有幫助,但在我的具體實例中,條件可能包括與另一個表的聯接(忘了在我原來的帖子中提到,抱歉),所以我猜這種方法不行。

+0

您使用的是哪種數據庫? – Andomar 2009-05-20 15:48:07

+0

MySQL,但我想知道它一般如果它非常簡單 – 2009-05-20 15:54:37

+0

相關但不是解決方案:你也可以用來獲得更大的表的計數。 SELECT SQL_CALC_FOUND_ROWSFROM MyTable; SELECT FOUND_ROWS(); SELECT SQL_CALC_FOUND_ROWSFROM MyTable WHERE {conditions}; SELECT FOUND_ROWS(); – 2009-05-20 16:03:23

回答

22

一種方法是加入表對本身:

select 
    count(*) as TotalCount, 
    count(s.id) as QualifiedCount 
from 
    MyTable a 
left join 
    MyTable s on s.id = a.id and {some conditions} 

另一種方法是使用子查詢:

select 
    (select count(*) from Mytable) as TotalCount, 
    (select count(*) from Mytable where {some conditions}) as QualifiedCount 

或者你可以把條件的情況下:

select 
    count(*) as TotalCount, 
    sum(case when {some conditions} then 1 else 0 end) as QualifiedCount 
from 
    MyTable 

相關:

SQL Combining several SELECT results

19

在SQL Server或MySQL,你可以做一個CASE語句:

select 
    count(*) as TotalCount, 
    sum(case when {conditions} then 1 else 0 end) as QualifiedCount 
from MyTable 

編輯:

select 
    count(*) as TotalCount, 
    sum(case when {conditions} then 1 else 0 end) as QualifiedCount 
from MyTable t 
left join MyChair c on c.TableId = t.Id 
group by t.id, t.[othercolums] 

的GROUP BY:如果您使用的條件JOIN這也適用是否確保您只能從主表中找到一行。

+1

只是想指出,這個例子會比任何聯合或聯合表現要好得多,因爲它只需評估有問題的表格 – kscott 2009-05-20 15:55:42

7

如果你只是計算行,你可以使用嵌套查詢。

select 
    (SELECT COUNT(*) AS TotalCount FROM MyTable) as a, 
    (SELECT COUNT(*) AS QualifiedCount FROM MyTable WHERE {conditions}) as b 
0

MySQL不計空值,所以這應該工作太:

SELECT count(*) AS TotalCount, 
    count(if(field = value, field, null)) AS QualifiedCount 
    FROM MyTable {possible JOIN(s)} WHERE {some conditions} 

,如果QuailifiedCount字段來自一個LEFT JOIN,你只當它存在在乎效果很好。要獲得用戶數量和已填寫地址的用戶數量:

SELECT count(user.id) as NumUsers, count(address.id) as NumAddresses 
    FROM Users 
    LEFT JOIN Address on User.address_id = Address.id;