what I am trying to do is prevent MySQL to select duplicated rows by the table primary key.
Please note, data is not real but just for the sake of the question.
prospect_evaluations
id | category | archived_at | discarded_at | hidden_at
1 | to_contact | null | null | null
2 | to_contact | null | null | null
3 | to_convert | null | null | null
4 | to_convert | null | null | null
prospect_evaluations_actions
id | evaluation_id | created_at
1 | 1 | 01-02-2017 01:00:00
2 | 1 | 01-02-2017 02:00:00
3 | 2 | 01-02-2017 03:00:00
SELECT prospect_evaluations.*,
prospect_evaluations_actions.evaluation_id,
prospect_evaluations_actions.created_at AS lastaction_created_at
FROM `prospect_evaluations`
LEFT JOIN `prospect_evaluations_actions` ON `prospect_evaluations_actions`.`evaluation_id` = `prospect_evaluations`.`id`
WHERE `prospect_evaluations`.`category` = 'to_contact'
AND `archived_at` IS NULL
AND `discarded_at` IS NULL
AND `prospect_evaluations`.`hidden_at` IS NULL
ORDER BY IFNULL( CAST(prospect_evaluations_actions.created_at AS date), CAST(prospect_evaluations.created_at AS date) ) DESC, `prospect_evaluations`.`priority` DESC
What's the query result?
id | category | archived_at | discarded_at | hidden_at | lastaction_created_at
1 | to_contact | null | null | null | 01-02-2017 01:00:00
1 | to_contact | null | null | null | 01-02-2017 02:00:00
2 | to_contact | null | null | null | 01-02-2017 03:00:00
What do I want instead?
id | category | archived_at | discarded_at | hidden_at | lastaction_created_at
1 | to_contact | null | null | null | 01-02-2017 02:00:00
2 | to_contact | null | null | null | 01-02-2017 03:00:00
EDIT: I've just noticed that results are duplicated depending on how many actions they have linked to the evaluation, like if the evaluation has had four actions in the history, it's gonna be duplicated four times. I only need the LAST action so that I can select the creation date and use it to order my entries!
EDIT 2: This situation, in comparison to what has been flagged as a possible duplicate, is different because this question consists of:
- SELECT of table1
- LEFT JOIN of table2.
The duplicated question instead consists of:
- SELECT of table1
- LEFT JOIN of table1