I have two of my SQL tables that I'm trying to join, they are simplified as:
+----------------------------+
| customers |
+-------------+-------+------+
| customer_id | first | last |
+-------------+-------+------+
| 0 | John | Doe |
+-------------+-------+------+
| 1 | Jane | Doe |
+-------------+-------+------+
+-------------------------------------------------------------------+
| contact_log |
+----------------+-------------+--------------+---------------------+
| contact_log_id | customer_id | contact_type | date_time |
+----------------+-------------+--------------+---------------------+
| 0 | 0 | email | 2016-05-17 03:21:45 |
+----------------+-------------+--------------+---------------------+
| 1 | 0 | phone | 2016-05-17 16:11:35 |
+----------------+-------------+--------------+---------------------+
| ... | ... | ... | |
+----------------+-------------+--------------+---------------------+
I need a request that will select customers and their last time and type of contact. I tried this query:
SELECT
`customers`.`customer_id`,
`customers`.`first`,
`customers.last`,
`contact_log`.`contact_type`,
MAX(`contact_log`.`date_time`)
FROM
`customers`
JOIN
`contact_log`
ON
`customers`.`customer_id` = `contact_log`.`customer_id`
It usually sorts incorrectly date_time. Investigating the problem, in some versions of MySQL there is an error, where MAXthey MINwork incorrectly with DATETIME. Therefore a workaround
MAX(CAST(`contact_log`.`date_time` AS CHAR))
So, I get client strings with the latter date_time. However, it contact_typedoes not correspond to the time. In the examples below, my result is as follows:
+-------------+-------+------+--------------+---------------------+
| customer_id | first | last | contact_type | date_time |
+-------------+-------+------+--------------+---------------------+
| 0 | John | Doe | email | 2016-05-17 16:11:35 |
+-------------+-------+------+--------------+---------------------+
contact_type date_time contact_log. , SELECT/JOIN, . ( n + 1), .
contact_type date_time?
, , . . , ?