我有一个包含两个表的数据库:
subscriber_mm
uid_local | uid_foreign | uid_partner
7 |2 |0
7 |4 |0
2 |1 |0
2 |2 |0
5 |1 |0
5 |3 |0
partner_mm
uid_local | uid_foreign | uid_partner
7 |1 |1
我的目标是根据两个表计算uid_local的总行数 例如:
count both tables by uid_local = 7
结果:3
示例:
count both tables by uid_local = 2
结果:2
这是我没有WHERE语句的解决方案(不是最好的)
SELECT sum(
ROWS ) AS total_rows
FROM (
SELECT count( * ) AS ROWS
FROM partner_mm
UNION ALL
SELECT count( * ) AS ROWS
FROM subscriber_mm
) AS u
我该如何实现WHERE语句?
答案 0 :(得分:1)
此处为您的查询传递值而不是2:
select sum(total_count ) as total_count from
(select count(*) as total_count from subscriber_mm s where s.uid_local=2
union all
select count(*) as total_count from partner_mm m where m.uid_local=2) as a
或
select a.uid_local,sum(total_count ) as total_count from
(select s.uid_local as uid_local, count(*) as total_count from subscriber_mm s group by s.uid_local
union all
select m.uid_local as uid_local, count(*) as total_count from partner_mm m group by m.uid_local) as a
group by a.uid_local
答案 1 :(得分:0)
无需执行SUM,因为您只需要计算特定uid_local
的两个表返回的总行数。可以使用UNION ALL
运算符获取总行数,这些运算符从两个表 WITHOUT 返回的结果集中删除重复记录
Select count(*) as Result From
(
Select * from subscriber_mm
where uid_local=7
union all
Select * from subscriber_mm
where uid_local=7
)as tmp
答案 2 :(得分:0)
请尝试
select uid_local,uid_foreign,uid_partner from subscriber_mm
union
select uid_local,uid_foreign,uid_partner from partner_mm
您可以使用Union For sum两个表行