点击表架构:
user_id as (integer)
created_at as (Y-m-d H:i:s)
观看表
user_id as (integer)
created_at as (Y-m-d H:i:s)
我需要按日期NOT日期时间计算第1表+第2表组中的记录:
现在我正在使用2个查询:
$clicks = $user->clicks()
->select(\DB::raw("DATE_FORMAT(created_at, '%d/%m/%Y') as date"),
\DB::raw("COUNT(*) as clicks"))
->groupBy('date')
->orderBy('date', 'ASC')
->get()->toArray();
$views = $user->views()
->select(\DB::raw("DATE_FORMAT(created_at, '%d/%m/%Y') as date"),
\DB::raw("COUNT(*) as views"))
->groupBy('date')
->orderBy('date', 'ASC')
->get()->toArray();
我有一个循环后
$out = [];
for ($i=0; $i < count($views); $i++) {
$out[] = [
'date' => $views[$i]['date'],
'clicks' => $clicks[$i]['clicks'],
'views' => $views[$i]['views']
];
}
但是这种方式如果点击存在并在某个日期查看否,则不会将其添加到阵列中 可以按日期格式加入created_at吗?没有时间?
答案 0 :(得分:1)
因为MySQL不支持完全加入试试这个
select date(clicks.created_at)as 'Date',
count(clicks.user_id) as 'clicks',
count(views.user_id)as 'views'
from clicks
left join views on date(views.created_at)=date(clicks.created_at)
group by date(clicks.created_at)
union
select date(views.created_at)as 'Date',
count(clicks.user_id) as 'clicks',
count(views.user_id)as 'views'
from views
left join clicks on date(views.created_at)=date(clicks.created_at)
group by date(views.created_at)
因为您在查询中有计数,请尝试此查询
select a.Date,a.clicks,b.views
from(select date(clicks.created_at)as 'Date',
count(clicks.user_id) as 'clicks'
from clicks
group by date(clicks.created_at))a
left join (select date(views.created_at)as 'Date',
count(views.user_id) as 'views'
from views
group by date(views.created_at))b
on a.date=b.date
union
select a.Date,b.clicks,a.views
from(select date(views.created_at)as 'Date',
count(views.user_id) as 'views'
from views
group by date(views.created_at))a
left join (select date(clicks.created_at)as 'Date',
count(clicks.user_id) as 'clicks'
from clicks
group by date(clicks.created_at))b
on a.date=b.date