如何通过特定查询获取最后日期的记录

时间:2017-08-09 14:13:15

标签: php mysql

我有表格货币和表格这个课程数据。我如何在上次约会前获得每种货币的一个课程数据 这是我的代码,我按日期获得每种货币的课程:

SELECT
    `coll_currency`.`collectionAlias`,
    `coll_currency`.`currency_abbr`,
    `coll_currency`.`currency_image`,
    `coll_currency`.`currency_name`,
    `coll_currency`.`currency_amount`,
    `coll_currency`.`id`,
    `pars_table`.`course` AS `currency_course`,
    `pars_table`.`publishdate` AS `currency_publishdate`,
    `pars_table`.`currency_id`
FROM
    `coll_currency`
INNER JOIN `pars_currency_nbu` AS `pars_table` 
   ON coll_currency.id = pars_table.currency_id
WHERE
    (
        (`currency_type` = '3670924')
        AND (`currency_state` = '3583429')
        AND (
            DATE_FORMAT(
                `pars_table`.`publishdate`,
                '%Y-%m-%d'
            ) = '2017-08-09'
        )
    )
ORDER BY
    `currency_publishdate` DESC

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

SELECT `c`.`collectionAlias`,
       `c`.`currency_abbr`,
       `c`.`currency_image`,
       `c`.`currency_name`,
       `c`.`currency_amount`,
       `c`.`id`,
       `p`.`course` AS `currency_course`,
       `p`.`publishdate` AS `currency_publishdate`,
       `p`.`currency_id` -- this has the same value as `c`.`id`
FROM `coll_currency` AS `c`
JOIN `pars_currency_nbu` AS `p` ON `c`.`id` = `p`.`currency_id`
JOIN ( SELECT `cc`.`id`, MAX(`pp`.`publishdate`) AS `maxdate`
       FROM `coll_currency` AS `cc`
       JOIN `pars_currency_nbu` AS `pp` ON `cc`.`id` = `pp`.`currency_id`
       GROUP BY `cc`.`id`
     ) AS `q` ON `q`.id` = `c`.`id` AND `q`.`maxdate` = `p`.`publishdate`