我有以下查询
SELECT c.`name` as categories,times_booked.booked as booked
FROM req_profiles rq
inner join categories as c on c.id = rq.category_id
left join
(
SELECT rq.id, COUNT(rq.id) as booked
FROM req_profiles as rq
inner join profile_matchings as pm on pm.req_profile_id = rq.id
WHERE pm.`status` = 'booked'
AND rq.user_id = 736
AND (pm.created_at BETWEEN '2018-01-01 00:00' AND '2019-02-13 00:00')
GROUP BY rq.id
) as times_booked on times_booked.id = rq.id
where rq.user_id=736
and rq.`status` = 'active'
ORDER BY times_booked.booked,rq.id desc
limit 5
这就是我得到的:
categories| booked
-------------------
Talent NULL
Talent 1
Talent 1
但我想得到这样的结果:
categories| booked
-------------------
Talent 2
感谢您的帮助!
最佳答案
使用您的查询作为子查询 anf group by
select categories, count(booked)
from (
SELECT c.`name` as categories,times_booked.booked as booked
FROM req_profiles rq
inner join categories as c on c.id = rq.category_id
left join
(
SELECT rq.id, COUNT(rq.id) as booked
FROM req_profiles as rq
inner join profile_matchings as pm on pm.req_profile_id = rq.id
WHERE pm.`status` = 'booked'
AND rq.user_id = 736
AND (pm.created_at BETWEEN '2018-01-01 00:00' AND '2019-02-13 00:00')
GROUP BY rq.id
) as times_booked on times_booked.id = rq.id
where rq.user_id=736
and rq.`status` = 'active'
ORDER BY times_booked.booked,rq.id desc
limit 5
) t
group by categories
关于SQL如何分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697959/