作者smallyou1988 ()
看板Database
标题[讨论] 关於两个table合并统计
时间Sat Jul 5 00:57:13 2014
大家好,小弟有个问题想问大家,如下:
有两个table分别叫 AA和BB
AA: BB:
------------------ -------------------
id | usage id | usage
------------------ -------------------
1 | 12 2 | 5
------------------ -------------------
2 | 4 3 | 3
------------------ -------------------
2 | 5 9 | 12
------------------ -------------------
9 | 80 11 | 1
------------------ -------------------
我想统计id in (1,2,3,9),我不要11:
------------------
id | count(usage)
------------------
1 | 12
------------------
2 | 14
------------------
3 | 3
------------------
9 | 92
------------------
所以我下了语法
select id,count(usage) from
(( select id,usage from AA ) union ( select id,usage from BB ))
where id in (1,2,3,9) group by 1 order by 1
这样是可行的
我想问问看大家对於这样的统计有什麽其他方式可做吗?
感谢大家! :D
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 114.37.221.44
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/Database/M.1404493035.A.D00.html
※ 编辑: smallyou1988 (114.37.221.44), 07/05/2014 00:57:50
1F:→ smallyou1988:打错,count要改sum XD 07/05 01:10
2F:→ hhomerun:group by 1 order by 1 你确定是这样子的吗~~~~~~~~~~~~ 07/05 01:57
恩,在我用的资料库这样下是可以的,其他种的资料库我就不知道了XD
3F:→ hhomerun:想改的话, 就 where 那边 可以变成 where id<10 或 id<=9 07/05 02:03
4F:→ hhomerun:但这是你想要听的答案吗 其实已经没甚麽好改了 07/05 02:04
5F:→ bohei:id应该有index? 原po的这写法会使用到index吗? 07/05 08:58
6F:→ bohei:先在里面把条件指定好不知道有没有差 07/05 08:59
恩,我有想过,我要筛选的两个table是几百万笔资料
7F:→ bohei:不过你应该要使用UNION ALL而不是UNION, UNION会把两个table 07/05 10:12
8F:→ bohei:重复的资料给剔除掉 07/05 10:12
9F:→ smallyou1988:事实上我要筛选的条件有三种,有两个是index,一个不是 07/05 12:13
※ 编辑: smallyou1988 (111.243.184.138), 07/05/2014 12:16:52
※ 编辑: smallyou1988 (111.243.184.138), 07/05/2014 12:18:08