I’m writing a complex MySQL query and I’m having trouble figuring out how to finish it.
Here’s the part that’s giving me trouble (it’s only a part of my query):
SELECT * FROM table AS t1
WHERE date < (
SELECT date FROM table AS t2
WHERE phase="B" AND t2.target = t1.target
)
Basically, I have items, each one with a date, a phase (A,B,C) and a target. For a target, there are several items of type A, then an single and optional item of type B, then items with type C.
For each target, I want to select all the rows following these conditions:
- If there is an item with phase “B” (lets call him itemX), I want to return all items with a date inferior to the date of itemX
- If there is no item with phase “B”, I want to return all rows
The date parameter is very important. In most cases, the 3 phases are distinct, and cannot overlap, but there are some cases in which that happens.
The problem here, is that my subquery does not return any rows in case 1, and a single cell in case 2.
If we are in case 1, the whole condition WHERE date < (...) is irrelevant and should not be applied in the query.
I tried several possibilities with IFNULL and EXISTS, but I think I did it wrong because I keep getting syntax errors.
Create two indexes:
for this to work fast.