views:

202

answers:

3

Is it possible to join two tables based on the same date, not factoring in time?

Something like:

...FROM appointments LEFT JOIN sales ON appointments.date = sales.date...

The only problem is it is a datetime field, so I want to make sure it is only looking at the date and ignoring time

A: 

the ON clause accepts an arbitrary conditional expression, so you can perform the date normalization in both sides before comparing, but it should represent a significant performance penalty.

Daniel Ruoso
A: 

Yes, but you have to join on a calculated expression, that strips the time from the datetime column values. This will make the query non-SARGable (It cannot use an index) so it will generate a table scan...

I don't know the syntax in mysql to strip time from a datetime value, but whatever it is, just write

   FROM appointments a 
      LEFT JOIN sales s 
         ON StripTime(s.date) = StripTime(a.date)
Charles Bretana
+4  A: 

You can do it like this:

FROM appointments
LEFT JOIN sales ON DATE(appointments.date) = DATE(sales.date)

But I'm pretty sure it won't be able to use an index, so will be very slow.

You might be better off adding a date column to each table.

Greg