I am trying to get data from two related tables in a single query.
Tables look like this:
Table 1:
--------------------------
| ID | username |
--------------------------
| 1 | user1 |
| 2 | user2 |
| 3 | user3 |
| 4 | user4 |
--------------------------
Table 2:
----------------------------------------------------
| ID | user_id | key | value |
----------------------------------------------------
| 1 | 1 | key1 | value1 |
| 2 | 1 | key2 | value2 |
| 3 | 2 | key2 | value3 |
| 4 | 3 | key3 | value4 |
| 5 | 4 | key1 | value5 |
| 6 | 4 | key3 | value5 |
----------------------------------------------------
I want to get a result including all rows from Table 1 and key-value pairs from table 2 where key = key1. If the key is not present in Table 1 for a given row from table 1, fill it with NULL. Expected result example:
----------------------------------------------------
| user_id | username | key | value |
----------------------------------------------------
| 1 | user1 | key1 | value1 |
| 2 | user2 | NULL | NULL |
| 3 | user3 | NULL | NULL |
| 4 | user4 | key1 | value5 |
----------------------------------------------------
Alternatively – all the rows from Table 1 which don’t contain key-value pair for key=key1 in Table 2.
I tried standard SELECT from 2 tables and SELECT from Table 1 with JOIN from Table 2, but all I get is all rows from Table 1 which contain key-value pair with key=key1 in Table 2 and this is exactly the opposite of what I want.
Any suggestions?
For your “Alternative” to get all that DO NOT have, just add a where clause..