I am having some difficulties wrapping my head around this issue. I’m sure there’s a work-around but I’m trying to use a single query. I am joining two tables with a couple of conditions. I need to return all rows matching the ‘t_id’ (even if NULL). I also need to join only the data matching’e_id’. If the ‘e_id’ does not exist, it should return NULL. The following query returns all of the rows that I need:
SELECT b.*, ev.* FROM blocks b
LEFT OUTER JOIN element_values ev ON ev.b_id = b.id
WHERE t_id = 1;
+----+------+-----------+-----+------+------+-----------------+
| id | t_id | type | pos | e_id | b_id | value |
+----+------+-----------+-----+------+------+-----------------+
| 1 | 1 | textinput | 1 | 1 | 1 | this is it edit |
| 2 | 1 | textinput | 0 | 1 | 2 | what is it |
| 5 | 1 | template | 2 | NULL | NULL | NULL |
+----+------+-----------+-----+------+------+-----------------+
But adding another condition for ‘e_id’ will return the accurate data, but will exclude the third row if it is NULL (of course).
SELECT b.*, ev.* FROM blocks b
LEFT OUTER JOIN element_values ev ON ev.b_id = b.id
WHERE t_id = 1 AND e_id = 1;
+----+------+-----------+-----+------+------+-----------------+
| id | t_id | type | pos | e_id | b_id | value |
+----+------+-----------+-----+------+------+-----------------+
| 1 | 1 | textinput | 1 | 1 | 1 | this is it edit |
| 2 | 1 | textinput | 0 | 1 | 2 | what is it |
+----+------+-----------+-----+------+------+-----------------+
I’m looking for a solution where all three rows are still returned if ‘e_id’ doesn’t exist. For example, with the last query, when I pass ‘e_id = 2’, the set will be empty. But, I need it to still return the all of the rows that equal the ‘t_id’.
Any thoughts are helpful.
Thanks!
You can inlcude the e_id = 1 in the LEFT JOIN clause to get the rows you want.
Change your query to as follows: