如何创建MySQL视图

问题描述 投票:2回答:2

我有MySQL访问表作为

visit_date        client_id
2019-01-01 08-00-00 1
2019-01-01 11-00-00 2

work_hours表为

hour    name
8        '08-00'
9        '09-00'
...
18        '18-00'

和表客户端

  client_id client_name
  1           aaa
  2           bbb 
  3           ccc

如何创建视图来获取数据?

client_id   hour_name    count
1        '08-00'    1
1        '09-00'    0   
.....
1        '18-00'    0
2        '08-00'    0
2        '09-00'    0
2        '10-00'    0
2        '11-00'    1
2        '12-00'    0
.....
2        '18-00'    0
3        '08-00'    0
3        '09-00'    0
.....    all zero
3        '18-00'    0
mysql sql cross-join
2个回答
2
投票

试试这个:

SELECT c.client_id, w.hour_name,
    (SELECT COUNT(1) 
    FROM visits v
    WHERE v.client_id = c.client_id
    AND HOUR(v.visit_date) = w.hour) as tot_visit
FROM clients c
CROSS JOIN work_hours w
ORDER BY c.client_id, w.hour_name

SQL Fiddle


0
投票
SELECT c.client_id,
       wh.hour_name,

  (SELECT count(1)
   FROM visits
   WHERE hour(visit_date) = wh.hour
     AND client_id=c.client_id) AS chcount
FROM work_hours wh,
     clients c;
© www.soinside.com 2019 - 2024. All rights reserved.