I’m having a bit of a problem with a SELECT query in MySQL and I’d be thankful for some pointers. Please feel free to point me towards an existing answer (if there is one and I missed it).
The query is currently as follows:
SELECT e.*, ie.aaa, ue.bbb, ue.ccc
FROM ie
LEFT JOIN e ON ie.e_id = e.e_id
LEFT JOIN ue ON ie.e_id = ue.e_id
WHERE ie.other_id = ? AND ue.unrelated_id = ?
ORDER BY ...
There are three tables: ie, e and ue.
Tables ie and ue are relationships of e, and therefore contain foreign keys to it (e_id). ? represents an input parameter.
The problem is the ue.unrelated_id = ? part. What I’m really trying to do here is:
- To return ue.ccc if and only if there is a ue relationship for unrelated_id = ?. If it doesn’t exist, I want this field to be null.
- Even if the ue relationship for unrelated_id = ? doesn’t exist, this query should always return the remaining fields (ie is guaranteed to exist for other_id = ?).
Unfortunately, if I remove this where clause, I get ue.ccc for a “random” unrelated_id. But if I keep it, the query won’t return any results at all if ue doesn’t exist for this unrelated_id! I also tried adding OR ue.unrelated_id IS NOT NULL, but this makes the query return no results if the ue table is empty.
Any ideas? Please drop a comment if you need further clarification. I should answer quickly in the next few hours.
You could do one of two things:
Or
I would go with the first query, however.
EDIT: Please note that the 2nd query is only approperiate if
ue.unrelated_idis not a nullable column.