SELECT *
FROM Contrato
WHERE (
(FechaBaja != FechaFin)
OR (FechaBaja NOT IN (SELECT FechaFinProrroga
FROM DatoAuxiliarContrato
WHERE (FechaFinProrroga != '') AND (FechaFinProrroga BETWEEN '20180101 00:00:00' AND '20181231 23:59:59')
)
)
)
AND (FechaBaja BETWEEN '20180101 00:00:00' AND '20181231 23:59:59')
The operator IN
will be true if the value is within the following list (a subquery is treated as a list).
If you want or know that there will only be one value in the subquery you can do:
SELECT *
FROM Contrato
WHERE (
(FechaBaja != FechaFin)
OR (FechaBaja != (SELECT FechaFinProrroga
FROM DatoAuxiliarContrato
WHERE (FechaFinProrroga != '') AND (FechaFinProrroga BETWEEN '20180101 00:00:00' AND '20181231 23:59:59')
LIMIT 1
)
)
)
AND (FechaBaja BETWEEN '20180101 00:00:00' AND '20181231 23:59:59')
Look at LIMIT 1
to ensure that no more than one value will be returned, which would give an error in the query.
You can find more information about the use of subqueries in the official documentation link
(edit)
According to the latest clarifications, it would be:
SELECT c.*
FROM Contrato AS c
WHERE (
(c.FechaBaja != c.FechaFin)
OR (c.FechaBaja NOT IN (SELECT aux.FechaFinProrroga
FROM DatoAuxiliarContrato AS aux
WHERE (aux.FechaFinProrroga != '')
AND (aux.FechaFinProrroga BETWEEN '20180101 00:00:00' AND '20181231 23:59:59')
AND (aux.CodContrato = c.DatoAuxiliarContrato)
)
)
)
AND (c.FechaBaja BETWEEN '20180101 00:00:00' AND '20181231 23:59:59')
I have added alias to the tables, to clarify a bit because FechaBaja
generates a lot of doubts.