0

I have the following MySQL tables:

[users]

| id | name    |
|----|---------|
| 1  | John    |
| 2  | Anna    |
| 3  | Peter   |

[times]

| user_ID | date       | time   |
|---------|------------|--------|
| 1       | 2020-03-20 | 07:00  |
| 1       | 2020-03-21 | 08:00  |
| 3       | 2020-03-22 | 09:00  |

my query look like:

SELECT name, date, time 
FROM users 
INNER JOIN times ON times.user_ID = users.id 
WHERE date = '2020-03-22';

what i get is:

| name    | date       | time   |
|---------|------------|--------|
| Peter   | 2020-03-22 | 09:00  |

what i want is:

| name    | date       | time   |
|---------|------------|--------|
| John    |            |        |
| Anna    |            |        |
| Peter   | 2020-03-22 | 09:00  |

is there a way to join non existent lines (not fields!) in the times table with the users table?

2
  • 1
    Consider storing date and time as a single entity Commented Mar 20, 2020 at 21:37
  • I would use UNION instead of an Inner Join Commented Mar 20, 2020 at 23:06

2 Answers 2

1

Use LEFT JOIN. And then you need to put the restrictions on the second table into the ON clause.

SELECT name, date, time 
FROM users 
LEFT JOIN times ON times.user_ID = users.id AND date = '2020-03-22';
Sign up to request clarification or add additional context in comments.

Comments

1

use left join and move where clause to on:

SELECT name, date, time 
FROM users 
left JOIN times ON times.user_ID = users.id and date = '2020-03-22';

2 Comments

thank you! that gave me the right idea of how this is working. i already supposed about using left and right joins but i did it wrong with the where clause. now i'm into it thanks! can i also replace null fields with some default values? (like '00:00:00')
@3x3cut0r Yes you can if the ifnull function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.