I am currently working on a little project. I have 2 tables AREA and ACTIVITY
table AREA
+---------------+
| a_id a_name |
+---------------+
| 1 area1 |
| 2 area2 |
| 3 area3 |
| 4 area4 |
+---------------+
table ACTIVITY
+-----------------------------------------------------+
| id areaid starttime endtime |
+-----------------------------------------------------+
| 1 1 2018-09-21 15:00:00 2018-09-21 17:00:00 |
| 2 2 2018-09-23 15:00:00 2018-09-21 18:00:00 |
| 3 1 2018-09-21 17:00:00 2018-09-21 19:00:00 |
| 4 4 2018-07-21 12:00:00 2018-07-21 13:30:00 |
+-----------------------------------------------------+
Now I want to select all areas and join the activity which is currently active or will be next started:
starttime >= NOW() AND endtime >= NOW()
starttime <= NOW() AND endtime >=NOW()
Also the areas with no active or upcoming activity should be shown.
I expect following result:
+-------------------------------------------------------+
| a_id id startime endtime |
+-------------------------------------------------------+
| 1 1 2018-09-21 15:00:00 2018-09-21 17:00:00 |
| 2 2 2018-09-23 15:00:00 2018-09-21 18:00:00 |
| 3 null null null |
| 4 null null null |
+-------------------------------------------------------+
I have tried several queries but I did not find the solution yet.
Currently this was my Best try:
SELECT *
FROM areas ar
LEFT JOIN activity a
ON ar.a_id = a.areaid
WHERE a.starttime >= NOW() AND a.endtime >= NOW() OR a.starttime <= NOW() AND a.endtime >= NOW()
ORDER BY a.starttime DESC;
I with this query I am able to find all results with active or upcoming activities. But how can I Limit the WHERE expression to just get one row for each foreign key?
Thank you in advance!