Table A
UHID SlotID Date
111 1 2019-12-22
222 1 2019-12-22
333 3 2019-12-22
444 1 2019-12-22
555 2 2019-11-25
666 3 2019-12-22
Table B (Slot)
ID Slot Max slot
1 Morning 3
2 Noon 5
3 Evening 2
4 Night 5
Now I want to get available slot from table B on date 2019-12-22
and less than Max
the result will look like Table B (Slot)
ID Slot Max slot
2 Noon 5
4 Night 5
Thanks
You will need a LEFT JOIN here and GROUP BY the table B rows. The COUNT condition then goes to the HAVING clause.
select b.*
from table_b b
left join table_a a
on a.SlotID = b.ID
and a.Date = '2019-12-22'
group by b.ID
having count(a.SlotID) < b.Max_slot
Result:
| ID | Slot | Max_slot |
| --- | ----- | -------- |
| 2 | Noon | 5 |
| 4 | Night | 5 |
Note: Depending on your server version, settings and keys you might need to include all columns from the table B in the GROUP BY clause.
group by b.ID, b.Slot, b.Max_slot
You will find more info in the docs .
I think you might be able to benefit from a CTE:
WITH slot_counts (slot_id, slot_count)
AS (SELECT slotid, count(*) FROM `tableA` WHERE `date` = '2019-12-22' GROUP BY slotid)
SELECT *
FROM `tableB`, slot_counts
WHERE `max slot` < slot_counts.slot_count
AND tableB.slot = slot_counts.slot_id;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.