0

I want get max value in query MySQL without MAX() function because it's very slow. Ideally I want with LEFT JOIN.

References :

https://dev.mysql.com/doc/mysql-tutorial-excerpt/5.7/en/example-maximum-column-group-row.html

INNER JOIN Results from Select Statement using Doctrine QueryBuilder

My Query MySQL :

SELECT
    fs.id AS subject,
    fpv.id AS post_version_id
FROM 
    forum_subject fs
    INNER JOIN
        forum_post_version fpv
        ON fpv.forum_subject_id = fs.id
WHERE
    fs.id IN (10817, 10818)

Results :

subject | post_version_id

10817 | 528385

10817 | 528386

10818 | 528387

10818 | 528388

I want to return only one line : the maximum post_version_id.

Thank you for considering that my real case is much more complex :

  • In my real case, this query is the continuation of other joins ;
  • More line in each tables (> 50 000)

EDIT : Original query :

  SELECT 
    f13_.id 
  FROM 
    forum_subject_version f14_
    LEFT JOIN forum_subject_version f15_ ON (
      f15_.forum_category_id = f14_.forum_category_id 
      AND f14_.forum_subject_id = f15_.forum_subject_id 
      AND f14_.id < f15_.id
    ) 
    INNER JOIN forum_subject f16_ ON f14_.forum_subject_id = f16_.id 
    INNER JOIN forum_post_version f17_ ON (f17_.forum_subject_id = f16_.id) 
    LEFT JOIN forum_post_version f18_ ON (
      f18_.forum_subject_id = f16_.id 
      AND f17_.forum_post_id = f18_.forum_post_id 
      AND f17_.id < f18_.id
    ) 
    INNER JOIN forum_post f13_ ON f17_.forum_post_id = f13_.id 
  WHERE 
    f14_.forum_category_id IN (217, 218)
    AND f15_.id IS NULL 
    AND f18_.id IS NULL
  • f14_ => 2400 lines
  • f15_ => 480 lines ↘ (LEFT JOIN FILTER)
  • f16_ => 480 lines =
  • f17_ => 24000 lines ↗
  • f18_ => 4800 lines ↘ (LEFT JOIN FILTER)
  • f13_ => 4800 lines =
  • I want LEFT JOIN FILTER again for 2 lines

Return 4800 lines (2400 in #217 forum_category_id, 2400 in #218 forum_category_id), I want 2 lines, one per forum category (1 in #217 forum_category_id, 1 in #218 forum_category_id).

I can't use ORDER + LIMIT and I don't want this : MIN/MAX vs ORDER BY and LIMIT. MySQL recommand LEFT JOIN for filter but I can not do it in my situation after f13_ alias. :)

Community
  • 1
  • 1
Gaylord.P
  • 1,539
  • 2
  • 24
  • 54

0 Answers0