How do I get the latest data one row from each group

Hello,

There is a Unix timestamp in the “calisma_zamani” column,
How can I group “gorev_adi” according to this column and get the row records from each group?
I can’t get the latest records as below, I wonder where the problem is?

$son_gorevler = $db->prepare(" SELECT MAX(calisma_zamani) AS calisma_zamani, gorev_adi, calistirilan_dosya, calistirma_ciktisi FROM zamanlanmisgorev_gunluk GROUP BY gorev_adi ORDER BY calisma_zamani DESC");
$son_gorevler->execute();
$son_gorevler_arr = $son_gorevler->fetchAll();

You should have an id column (auto-increment primary index.) The maximum id per group is the latest/last row in the group.

The following should work -

$sql = "SELECT the columns you want
	FROM zamanlanmisgorev_gunluk
	WHERE id IN(SELECT MAX(id) FROM zamanlanmisgorev_gunluk GROUP BY gorev_adi)";
1 Like

Thank you very much.

I never thought such a query was necessary.

Some database platforms, like PostgreSQL, offer window functions that can simplify this task. For example, you can use the MIN() and OVER() functions with a partition by clause to directly select the desired rows.

Sponsor our Newsletter | Privacy Policy | Terms of Service