The query looks right, assuming that code
is a unique (or primary) key on the tgc_sales
table, and sales_code
is a foreign key reference to that column.
The use of the DATE()
function seems a bit odd.
If the sales_date_time
column has a datatype of DATE, DATETIME, or TIMESTAMP, then the DATE()
function isn't needed, and it's not desirable because it disables MySQL's ability to use an index range scan to satisfy the predicate.
If the sales_date_time
is character, and your intent is to convert the character into a DATE, you'd use the STR_TO_DATE()
function. But you don't really want to store sales_date_time
as a character string.
If that's a DATETIME column, you'd do something like this:
WHERE ts.sale_date_time >= '2014-05-01'
AND ts.sale_date_time < '2014-06-01'
If it's a character column in a non-canonical format (e.g. 'mm/dd/yyyy hh:mi:ss'), then you could do something like:
WHERE STR_TO_DATE(ts.sale_date_time,'%m/%d/%Y %h:%i:%s') >= '2014-05-01'
AND STR_TO_DATE(ts.sale_date_time,'%m/%d/%Y %h:%i:%s') < '2014-06-01'
(But you don't really want to store a date time value in a character string; you want to use one of the MySQL datatypes like DATETIME.)
If you're storing a unix-style timestamp "seconds since the beginning of an era", then you'd want to do the comparison against the native column values. You could do something like this:
WHERE ts.sale_date_time >= UNIX_TIMESTAMP('2014-05-01')
AND ts.sale_date_time < UNIX_TIMESTAMP('2014-06-01')
...though you'd really prefer to use the same library used to do the conversion when the values were stored, and do the query more like this:
WHERE ts.sale_date_time >= 1398902400
AND ts.sale_date_time < 1401580800