MySQL Query – Selecting Only the First Row of Each Value in MySQL

greatest-n-per-groupMySQLmysql-5.7

MYSQL version 5.7.31

How do I make it show the distinct rows of the value/column mainthreadid with the highest value of date?

Note that the data is filtered using

WHERE approved = 1 AND section != 150 

A fiddle is available here.

Fiddle DDL and DML

Table

CREATE TABLE forum (
    id int,
    mainthreadid int,
    section int,
    approved int,
    date int(20),
    title varchar(255),
    text varchar(255)
   
);

Sample Data

INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (1, 1, 5, 1, 1000, "title1", "text1");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (2, 2, 5, 1, 1000, "title2", "text2");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (3, 2, 5, 1, 1001, "title3", "text3");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (4, 2, 5, 1, 1002, "title4", "text4");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (5, 2, 5, 1, 1003, "title5", "text5");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (6, 2, 5, 1, 1004, "title6", "text6");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (7, 2, 5, 0, 1005, "title7", "text7");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (8, 8, 150, 1, 1004, "title8", "text8");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (9, 1, 5, 1, 1006, "title9", "text9");
INSERT INTO forum (id, mainthreadid, section, approved, date, title, text)
VALUES (10, 1, 5, 1, 1005, "title10", "text10");

SQL Statement

SELECT date, id, mainthreadid 
FROM `forum` 
WHERE approved = 1 AND section != 150 ORDER BY date DESC

Resultset

My desired result set would be:

date    id  mainthreadid
1006    9   1
1004    6   2

Best Answer

Maybe you need in

SELECT forum.*
FROM forum
JOIN ( SELECT mainthreadid, MAX(`date`) `date`
       FROM forum
       GROUP BY mainthreadid ) lastdates USING (mainthreadid, `date`)

?

fiddle

For each mainthreadid only last row (the row with greatest date) is selected. If there exists more than one such row (the same maximal date) then all of them will be returned.


you dont include checks for approved = 1 and if section != 150

No problems.

SELECT forum.*
FROM forum
JOIN ( SELECT mainthreadid, MAX(`date`) `date`
       FROM forum
       WHERE approved = 1 AND section != 150
       GROUP BY mainthreadid ) lastdates USING (mainthreadid, `date`)

fiddle