我想计算两个表的行,我写了这段代码:
SELECT count(v.id), count(c.id)
FROM votes as v, content as c
WHERE v.user_id=1 AND c.created_by=1
它正确地返回一行和两列,只有这两个单元具有完全相同的值...并且不应该如此
答案 0 :(得分:3)
您的查询正在两个表之间进行交叉连接。如果要计算行数,则需要以下内容:
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
答案 1 :(得分:2)
您需要计算不同的值,否则您只需计算相应列中包含ID的行数(除非您在某些ID中有NULL
,否则将是所有行):
count(DISTINCT v.id), count(DISTINCT c.id)
答案 2 :(得分:0)
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(*)计数。因此,这应该会给你你的结果。
答案 3 :(得分:0)
如果您希望数据位于同一行,则可以使用UNION ALL
,然后使用CASE
语句:
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
答案 4 :(得分:0)
仅在所选id不为空时计数
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