|
我有一张表,每个日期都有一些统计信息,我想用MySQL列出。对于某些日期,将没有统计信息,因此结果应与以下内容相似:
% b5 S% s. [& E; v& {2013-03-01:3 _+ Y4 y$ l i" V. ~. e
2013-03-02:2& y4 g2 p8 ~7 d& J4 v6 u# {; D
2013-03-03:0
( C, R/ T/ g0 s. j4 B& Z: |0 T2013-03-04:1
/ N& \+ Y+ U' @ d6 c我发现我可以用一个单独的表(包括所有可能的日期和LEFT JOIN)来解决用0-零-填补空白的问题。到目前为止,一切都很好。- i, B( h! n) O& y Y- p# [: q$ _
统计信息(显示次数)campaigndata”表中:0 o. `* X+ M5 q- B( J/ A6 W
id-int(11)日期-日期campaignid-int(11)印象数-int(11)但我只想得到一些统计信息。更具体地说,我只想来自 campaigndata campaignid”位于表“: e( e* |5 M% K3 W9 ~
campaignfilter”中,并且“ campaigntype设置为1(例如)。
$ d, L7 p: l7 L% }2 d- @: R这是表“ campaignfilter”: n7 u6 w5 y0 u/ k) r' P- O
id-int(11)campaigntype-int(11)campaignid-int(11)每个人都知道如何做到这一点?
4 m3 b% _8 t0 QPS:“ campaigndata由于它是基于从外部系统自动导入的结构,表的结构已被锁定。
/ w* F4 r# j6 [/ I, L4 T: d) N样本记录
. Z- p! u1 t. F/ Q5 B1 U- VCREATE TABLE demo_campaigndata ( id int(11) NOT NULL AUTO_INCREMENT, date date NOT NULL, campaignid int(11) NOT NULL, impressions int(11) NOT NULL, PRIMARY KEY (id));INSERT INTO demo_campaigndata (id,date,campaignid,impressions) VALUES(1,'2013-03-03,1,100),(2,2,2013-03-03,2,100),(3,2013-03-2013-03-04,2,100),(5,2013-03-(6)-03-05',2,100);CREATE TABLE demo_campaignfilter ( id int(11) NOT NULL AUTO_INCREMENT, campaigntype int(11) NOT NULL, campaignid int(11) NOT NULL, PRIMARY KEY (id));INSERT INTO demo_campaignfilter (id,campaigntype,campaignid) VALUES(1,1,1),(2,1,3);CREATE TABLE demo_calendar ( date date NOT NULL, PRIMARY KEY (date));INSERT INTO demo_calendar (date) VALUES('2013-03-01'),('2013-03-02'),('2013-03-03'),('2013-03-04'),('2013-03-05');期望的结果
+ I9 ?' L! f) n0 j# K8 D! N6 M3 g0 z2013-03-01: 02013-03-02: 02013-03-03: 2002013-03-04: 02013-03-5:100
' r1 T1 s. v# M; r6 T* J* j! I 解决方案:
& V7 W3 q$ t# m+ _ SELECT a.date,COUNT(b.campaignid) totalStat. {0 M8 }) y V$ U6 R1 R X
FROM campaigndata a0 m& P- C3 w; Z% A) p' q) j
LEFT JOIN campaignfilter b
4 s( t' Q' h& B( O5 y2 u/ I% H2 B ON a.campaignid = b.campaignid AND8 T1 N; }" r8 o, I) E% U) j
b.campaigntype = 1
; T6 C3 _$ d2 R2 i. O" L2 C GROUP BY a.date
- q# h3 v# W5 u' k为进一步获取相关知识,请访问以下链接:6 t) i9 }8 r% Z1 B* g/ \7 c
SQL可视表示连接更新1
) @% a9 X8 ?. aSELECT a.date, COALESCE(b.totals,0) totalsFROM demo_calendar a LEFT JOIN SELECT a.date,SUM(impressions) totals FROM demo_campaigndata a INNER JOIN demo_campaignfilter b ON a.campaignid = b.campaignid WHERE b.campaigntype = GROUP BY a.date b ON a.date = b.date |
|