Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL get all users who was in work in exact week

I have 2 tables: users and users_arrivals, I need to create a list of users who was in work in specific ranges of dates. Users table looks like:

| id | firstName | lastName |
| -- | --------- | -------- |
| 1  | John 1    | Test 1   |
| 2  | John 2    | Test 2   |
| 3  | John 3    | Test 3   |
| 4  | John 4    | Test 4   |

users_arrivals:

| id | user_id | start_date |  end_date  | 
| -- | ------- | ---------- | ---------- |
|  1 |       1 | 2022-09-01 | 2022-09-30 |
|  2 |       2 | 2022-09-22 | 2022-09-25 |
|  3 |       3 | 2022-09-19 | 2022-09-25 |

And now I need to get all users who was in work between dates 2022-09-19 and 2022-09-25 but some users have range 2022-09-01 and 2022-09-30 and also should be returned. I tried to make SQL like that but it only returns users who have range smaller or same as 2022-09-19 and 2022-09-25. How I can get users who have bigger range?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT *
FROM users u
LEFT JOIN users_arrivals po ON po.user_id = u.id
WHERE po.start_date BETWEEN '2022-09-19' AND '2022-09-25' AND po.end_date    BETWEEN '2022-09-19' AND '2022-09-25' 
GROUP BY u.id

>Solution :

Maybe something like this:

SELECT *
FROM users u
LEFT JOIN users_arrivals po ON po.user_id = u.id
WHERE '2022-09-19' BETWEEN po.start_date AND po.end_date    
OR    '2022-09-25' BETWEEN po.start_date AND po.end_date;

https://dbfiddle.uk/xf54UzPg

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading