我想计算表中记录的总数,以及匹配特定条件的记录总数。我可以通过两个单独的查询来完成这些操作:
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答案很有帮助,但在我的具体实例中,条件可能包括与另一个表的JOIN(忘了在我原来的帖子中提到,抱歉)所以我猜这种方法不起作用。
答案 0 :(得分: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
相关:
答案 1 :(得分:20)
在Sql Server或MySQL中,您可以使用CASE语句执行此操作:
select
count(*) as TotalCount,
sum(case when {conditions} then 1 else 0 end) as QualifiedCount
from MyTable
编辑:如果你在条件中使用JOIN,这也有效:
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用于确保您只从主表中找到一行。
答案 2 :(得分:7)
如果您只是计算行数,则可以使用嵌套查询。
select
(SELECT COUNT(*) AS TotalCount FROM MyTable) as a,
(SELECT COUNT(*) AS QualifiedCount FROM MyTable WHERE {conditions}) as b
答案 3 :(得分:1)
在Oracle SQL Developer中,我必须在选择中添加* FROM,否则我遇到语法错误:
select * FROM
(select COUNT(*) as foo FROM TABLE1),
(select COUNT(*) as boo FROM TABLE2);
答案 4 :(得分:0)
MySQL不计算NULL,所以这也应该有效:
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;