MySQL-两表有重复数据,如何高效的得到去掉重复条目后两表总数

发布于 2016-12-29 09:19:26 字数 310 浏览 1309 评论 2

a表

Qid               pname       Time        
aaaa... A组 2011-2-1
zzzz... A组 2011-2-1
bbbb... A组 2011-2-7
cccc.. B组 2011-2-2
dddd.. C组 2011-2-3
eeee... B组 2011-2-1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

虐人心 2017-03-14 22:41:19

 SELECT Time, panme, atmp.aCount, btmp.bCount, (atmp.aCount+btmp.bCount) AS total FROM (SELECT Time, panme,COUNT(Qid) AS aCount FROM a GROUP BY Qid) AS atmp
LEFT JOIN (SELECT Time, panme, COUNT(Qid) AS bCount FROM b GROUP BY Qid) AS btmp ON atmp.Qid = btmp.Qid
ORDET BY Time

偏爱自由 2017-02-28 21:54:23

下面是我测试的sql,里面包括创建临时表结构及数据:

create table a(Qid varchar(20),pname varchar(20),Time varchar(20));
create table b(Qid varchar(20),pname varchar(20),Time varchar(20));

insert into a values('aaaa...','A组','2011-2-1');
insert into a values('zzzz...','A组','2011-2-1');
insert into a values('bbbb...','A组','2011-2-7');
insert into a values('cccc...','B组','2011-2-2');
insert into a values('dddd...','C组','2011-2-3');
insert into a values('eeee...','B组','2011-2-1');

insert into b values('aaaa...','A组','2011-2-1');
insert into b values('bbbb...','A组','2011-2-7');
insert into b values('eeee...','B组','2011-2-1');
insert into b values('ffff...','W组','2011-2-5');
insert into b values('xxxx...','A组','2011-2-1');
insert into b values('yyyy...','A组','2011-2-1');

//查询sql
SELECT t.Time,t.pname,sum(t.Acount),sum(t.Bcount),t2.total 
FROM 
(
    SELECT Time,pname,count(pname) AS aCount,'0' as bCount FROM a GROUP BY pname,Time 
    UNION ALL 
    SELECT Time,pname,'0' AS aCount,count(pname) AS bCount FROM b GROUP BY pname,Time
)t 
LEFT JOIN  
(
    SELECT Time,pname,count(DISTINCT Qid) AS total FROM(SELECT * FROM a UNION ALL SELECT * FROM b)m GROUP BY pname,Time
)t2 on t.pname=t2.pname and t.Time=t2.Time 
GROUP BY pname,Time 
ORDER BY Time;

select 结果:

+----------+-------+---------------+---------------+-------+
| Time     | pname | sum(t.Acount) | sum(t.Bcount) | total |
+----------+-------+---------------+---------------+-------+
| 2011-2-1 | A组   |             2 |             3 |     4 |
| 2011-2-1 | B组   |             1 |             1 |     1 |
| 2011-2-2 | B组   |             1 |             0 |     1 |
| 2011-2-3 | C组   |             1 |             0 |     1 |
| 2011-2-5 | W组   |             0 |             1 |     1 |
| 2011-2-7 | A组   |             1 |             1 |     1 |
+----------+-------+---------------+---------------+-------+
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文