我想计算两个表的行数,我写了这段代码:
SELECT count(v.id), count(c.id)
FROM votes as v, content as c
WHERE v.user_id=1 AND c.created_by=1
它正确返回一行和两列,只有这两个单元格具有完全相同的值......而且不应该如此
我想计算两个表的行数,我写了这段代码:
SELECT count(v.id), count(c.id)
FROM votes as v, content as c
WHERE v.user_id=1 AND c.created_by=1
它正确返回一行和两列,只有这两个单元格具有完全相同的值......而且不应该如此
您的查询正在两个表之间进行交叉连接。如果要计算行数,则需要以下内容:
select 'vote' as which, count(*)
from votes v
where v.user_id = 1
union all
select 'content' as which, count(*)
from content c
where c.created_by = 1
如果您正在寻找一行、两列,请改用交叉连接:
select vcnt, ccnt
from (select count(*) as ccnt
from votes v
where v.user_id = 1
) v cross join
(select count(*) as ccnt
from content c
where c.created_by = 1
) c
您需要计算不同的值,否则您只需计算相应列中包含 ID 的行数(这将是所有行,除非您NULL
在某些 ID 中有 s):
count(DISTINCT v.id), count(DISTINCT c.id)
仅当所选 id 不为 null 时才计数
SELECT SUM(ISNULL(v.id,0,1)), SUM(ISNULL(c.id,0,1))
FROM votes as v, content as c
WHERE v.user_id=1 AND c.created_by=1
但是如果你需要单独计算,按照这个。
SELECT
(SELECT COUNT(*) FROM votes as v WHERE v.user_id=1) AS Count1,
(SELECT COUNT(*) FROM content as c WHERE c.created_by=1) AS Count2
SELECT
COUNT(Votes.id) VotesCount,
COUNT(Content.id) ContentCount
FROM
Votes
FULL OUTER JOIN Content ON 1=2 --Ensures rows never join
这会将两个表连接在一起,但不匹配任何行。因此,对于 Votes 中的每一行,所有 Content 列都将为 NULL,反之亦然。COUNT(ColumnName) 不计算 NULL 值,但 COUNT(*) 计算。因此,这应该给你你的结果。
如果您希望数据在同一行中,则可以使用 aUNION ALL
和 thenCASE
语句:
select max(case when col = 'voteCount' then cnt end) as voteCount,
max(case when col = 'ContentCount' then cnt end) as ContentCount
from
(
select count(*) cnt, 'voteCount' col
from votes v
where v.user_id = 1
union all
select count(*) cnt, 'ContentCount' col
from content c
where c.created_by = 1
) x