简体   繁体   中英

MySQL - given multiple associations, how to get latest association for several records?

Let's say I have two tables (non-essential rows omitted):

Table `pages`
page_id | page_key 
      1 |     home
      2 |    about

and

Table `page_versions`
page_id | page_version | page_title | page_content
      1 |            2 |       Home | Lorem Ipsum...
      1 |            4 |       Home | Dolor Sit...
      2 |            3 |      About | Nunc Nisl...
      2 |            5 |      About | Proin Alt...

If each page has multiple page_version s, how do I query the database such that I get all page s associated to their latest page_version ?

Essentially:

page_id | page_key | page_version | page_title | page_content
      1 |     home |            4 |       Home | Dolor Sit...
      2 |    about |            5 |      About | Proin Alt...

I prefer to do the subquery in the FROM clause as a derived table , so it will run the subquery only once.

SELECT p.page_id, p.page_key, pv.page_version, pv.page_title, pv.page_content 
FROM page_versions pv
INNER JOIN (SELECT page_id, MAX(page_version) AS page_version
    FROM page_versions GROUP BY page_id) AS max_page_versions
   USING (page_id, page_version)
INNER JOIN pages p USING (page_id);

Compare with the answer from @FilipeSilva which executes a correlated subquery once for each row of the outer query. That's likely to be bad for performance.

You can do this with a subselect first join and then order your table by page versions then in other select group them

SELECT * FROM (
SELECT p.*, ps.`page_version`,ps.`page_title`,ps.`page_content` FROM `page` p
LEFT JOIN  `page_versions` ps ON (p.`page_id`= ps.page_id) 
ORDER BY ps.`page_version` DESC ) newpage
GROUP BY newpage.`page_id`

See Updated fiddle here

You can do:

SELECT p.page_id, page_key, page_version, page_title, page_content 
FROM pages p
INNER JOIN page_versions pv ON pv.page_id = p.page_id
WHERE page_version = (SELECT MAX(page_version) 
                      FROM page_versions pv2 
                      WHERE pv2.page_id = pv.page_id)

SQLFIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM