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?

GMB
  • 216,147
  • 25
  • 84
  • 135
3x3cut0r
  • 1
  • 1

2 Answers2

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';
Barmar
  • 741,623
  • 53
  • 500
  • 612
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';
Jens
  • 67,715
  • 15
  • 98
  • 113
  • 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 Mar 21 '20 at 09:33
  • @3x3cut0r Yes you can if the [ifnull](https://www.w3schools.com/sql/func_mysql_ifnull.asp) function – Jens Mar 21 '20 at 09:55