mysql join donde la diferencia entre valores es mínima?

In principle I have 2 tables T1 and T2, each containing a date-field, lets call it date:

T1: date | somekey  | data ... 
T2: date | somekey  | data ...

Quiero (left)join T1 and T2, such that the result has all rows from T1.

Now for each row from T1 I need the values from the (exactly one) row of T2 joined where ABS(DATEDIFF(T1.date,T2.date)) is minimal and T1.somekey=T2.somekey (or null in case there is no such row in T2)

preguntado el 12 de junio de 12 a las 09:06

What do you mean with 'minimal difference' -

as far as i know DATEDIFF yields an integer value representing the difference in days between two dates. if there are rows in T2 that match the condition, there must be one particular row where that difference is minimal. My apology, I couldn't express that more clearly. -

1 Respuestas

No lo hagas en el JOIN clause, just put it in the WHERE cláusula.

SELECT
*
FROM
T1
LEFT JOIN T2 ON T1.somekey = T2.somekey
WHERE
ABS(DATEDIFF(T1.date,T2.date)) = 1 /*or whatever "minimal" means for you*/
/*or like this:*/                < $yourMinimalValue

EDIT:

I think I get what you want to do, but subqueries are the way to go here:

SELECT
*
FROM
T1
LEFT JOIN T2 ON T1.somekey = T2.somekey
WHERE
ABS(DATEDIFF(T1.date,T2.date)) = (SELECT MIN(DATEDIFF(TT1.date, TT2.date)) FROM  T1 AS TT1 LEFT JOIN T2 AS TT2 ON TT1.somekey = TT2.somekey)

Respondido el 12 de junio de 12 a las 09:06

That is the problem: minimal is not a constant value. - IARI

@IARI So do you want to select the row with the smallest DATEDIFF? It's still not completely clear to me as to what you are trying to accomplish. - akalucas

@akalucas I think that's what he wants, yes. - pantalones de lujo

@tombom Yes, that's exactly what I wanted. Also if the subquery is not in the from clause it is ok. I think you can delete the first suggestion from the post, the second one is the interesting case. - IARI

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.