我一直试图将来自两个查询的结果合并到一个表中以对它们进行计数并按小时排序。
我尝试过SELECT
和UNION ALL
,但是没有运气。
我已经搜索了所有StackOverflow和google,但始终无所适从。
如果我只运行一次查询-一切都很好,我将获得输出。
查询1:
SELECT COUNT(*) as peopleCount, date_format( timestamp, '%H' ) as hours
FROM unknownCheckin
WHERE timestamp > '2019-03-01 23' and eid = '222'
GROUP BY hours
order by timestamp ASC
查询2:
SELECT COUNT(*) as peopleCount, date_format( timestamp, '%H' ) as hours
FROM checkin
WHERE timestamp > '2019-03-01 23' and eid = '222'
GROUP BY hours
order by timestamp ASC
我的实验是:
SELECT COUNT(*) as peopleCount, date_format( timestamp, '%H' ) as hours FROM unknownCheckin
INNER JOIN checkin
ON unknownCheckin.eid = checkin.eid
WHERE timestamp > '2019-03-01 23' and eid = '222'
GROUP BY hours order by timestamp ASC
如果运行单个query1,则预期结果:
--------------------------------------------------
| peopleCount | hours |
--------------------------------------------------
| 4 | 21 |
--------------------------------------------------
| 1 | 22 |
--------------------------------------------------
| 1 | 00 |
--------------------------------------------------
查询2:
--------------------------------------------------
| peopleCount | hours |
--------------------------------------------------
| 10 | 22 |
--------------------------------------------------
| 22 | 23 |
--------------------------------------------------
| 12 | 00 |
--------------------------------------------------
| 5 | 01 |
--------------------------------------------------
我想看的是:
--------------------------------------------------
| peopleCount | hours |
--------------------------------------------------
| 4 | 21 |
--------------------------------------------------
| 11 | 22 |
--------------------------------------------------
| 22 | 23 |
--------------------------------------------------
| 13 | 00 |
--------------------------------------------------
| 5 | 01 |
--------------------------------------------------
对不起,我的思维能力不足。 帮助表示赞赏!
答案 0 :(得分:1)
也许您想在此处使用联合:
SELECT
hours,
COUNT(*) as peopleCount
FROM
(
SELECT DATE_FORMAT(timestamp, '%H') AS hours
FROM unknownCheckin
WHERE timestamp > '2019-03-01 23' AND eid = '222'
UNION ALL
SELECT DATE_FORMAT(timestamp, '%H')
FROM checkin
WHERE timestamp > '2019-03-01 23' AND eid = '222'
) t
GROUP BY hours
ORDER BY -FIELD(hours, '23', '22');
答案 1 :(得分:0)
对两个查询进行联合,然后获得peopleCount的总和:
select
t.hours,
sum(t.peopleCount) peopleCount
from (
SELECT COUNT(*) as peopleCount, date_format( timestamp, '%H' ) as hours
FROM unknownCheckin
WHERE timestamp > '2019-03-01 23' and eid = '222'
GROUP BY hours
union all
SELECT COUNT(*) as peopleCount, date_format( timestamp, '%H' ) as hours
FROM checkin
WHERE timestamp > '2019-03-01 23' and eid = '222'
GROUP BY hours
) t
group by t.hours