SELECT *
FROM `primary`
WHERE `id` IN (
SELECT `s`.`primary_id`
FROM (
SELECT `primary_id`, MAX(`datetime`) AS `datetime`
FROM `secondary`
GROUP BY `primary_id`
) AS `t`
JOIN `secodary` AS `s` ON `s`.`state` = 1
AND `s`.`primary_id` = `t`.`primary_id`
AND `s`.`datetime` = `t`.`datetime`
)