P
P
pavlikmd2018-05-07 15:08:33
MySQL
pavlikmd, 2018-05-07 15:08:33

How to display records by date and without duplicates from MySQL?

Hello, there is a task, there are about 14 million records in the database, there are records that are the same only differ in date, you need to display one record with the latest date.
I do this
$tableRows = $db->getAll("SELECT * FROM `dk_products` WHERE article = $article GROUP BY brand ORDER BY STR_TO_DATE(date,'%d.%m.%Y') DESC");
Displays one but only the very first date
5af040fbd2739892476909.png
. If I remove GROUP BY, it displays correctly, but only one is needed.
5af0415a06e98285115172.png
Putting LIMIT 1 is also not an option, since there can be 2 different brands with the same article.
The essence is to display the last record that is closer to today's date.
I am using SafeMySql.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
pavlikmd, 2018-05-07
@pavlikmd

I made the field type 'date' in MySQL and displayed it like this:

SELECT * FROM `dk_products` WHERE article = $article GROUP BY brand ORDER BY date DESC

A
Alexander Aksentiev, 2018-05-07
@Sanasol

group by concat(brand, date) order by date desc

R
Rsa97, 2018-05-07
@Rsa97

SELECT `t1`.*
  FROM `dk_products` AS `t1`
  LEFT JOIN `dk_products` AS `t2` ON `t1`.`article` = :article 
    AND `t2`.`article` = :article 
    AND `t2`.`brand` = `t1`.`brand`
    AND `t2`.`date` > `t1`.`date`
  WHERE `t2`.`article` IS NULL

SELECT `t2`.*
  FROM (
    SELECT `brand`, MAX(`date`) AS `date`
    FROM `dk_products`
    WHERE `article` = :article
    GROUP BY `brand`
  ) AS `t1`
  JOIN `dk_products` AS `t2` ON `t2`.`article` = :article
    AND `t2`.`brand` = `t1`.`brand`
    AND `t2`.`date` = `t1`.`date`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question