我想在数据库到图表中显示我的数据,这里使用谷歌图表。
问题是,当我计算并加入表格时,当两个表格中的日期不同时,数据不会显示。
例如,我有这样的数据。表1
date(table1) sh_sh
--------- ------------
2018-04-25 data1
2018-04-26 data2
2018-04-27 data3
表2
date(table2) ip
--------- ------------
2018-04-28 data1
2018-04-25 data2
2018-04-24 data3
我运行这样的代码,我从my question before
获得了这段代码SELECT urls.date, urls.count AS sh_count, ip.count AS ip_count FROM
(SELECT date(date) AS date, COUNT(*) AS count FROM table1 GROUP BY date(date)) AS urls JOIN
(SELECT date(date) AS date, COUNT(*) AS count FROM table2 GROUP BY date(date)) AS ip ON urls.date = ip.date
输出
date(url) count(sh_sh) count(ip)
--------- ------------ ----------
2018-04-25 1 1
日期 24,26,27,28 未显示导致日期不同。
我必须做什么,以不同的表和日期显示数据。
如果没有数据我想打印 0 。
这是我的图表脚本
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Urls', 'Clicks'],
<?php
while ($areacharts = $areachart->fetch()) {
echo "['".$areacharts['date']."',".$areacharts['sh_count'].",".$areacharts['ip_count']."],";
} ?>
]);
var options = {
hAxis: {title: 'Date', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('summary_chart'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
</script>
答案 0 :(得分:1)
使用UNION ALL
加入两个结果,
然后再次组合日期,
像这样......
SELECT
a.date AS date,
SUM(a.count) AS count
FROM (
SELECT date(date) AS date, COUNT(*) AS count FROM sh_url GROUP BY date(date)
UNION ALL
SELECT date(date) AS date, COUNT(*) AS count FROM tracking GROUP BY date(date)
) a
GROUP BY
a.date
答案 1 :(得分:1)
这个怎么样:
SELECT
a.`date`,
sum(a.sh_sh_cnt) as sh_sh_cnt,
sum(a.ip_cnt) as ip_cnt
FROM(SELECT
`date`,
count(*) as sh_sh_cnt,
sum(0) as ip_cnt
FROM table1
GROUP BY `date`
UNION ALL
SELECT
`date`,
sum(0) as sh_sh_cnt,
count(*) as ip_cnt
FROM table2
GROUP BY `date`) a
GROUP BY a.`date`
它不是很漂亮,但它应该有用。
使用相同的数据,这应该返回:
date sh_sh_cnt ip_cnt
---- --------- ------
2018-04-24 0 1
2018-04-25 1 1
2018-04-26 1 0
2018-04-27 1 0
2018-04-28 0 1
另外,请不要将日期字段命名为“日期”。这是一个保留字......你不想对字段名使用保留字!它会起作用,不要误会我的意思,但这是非常非常糟糕的做法!