简体   繁体   中英

Is this possible in a single mysql query?

I have two tables with a one to many relationship, offer and offer_rows

I want to fetch multiple offers with their content rows. That on it's own is not difficult, I just use an

 INNER JOIN on offer.offer_id = offer_rows.offer_id

However, the offer_rows table contains a field called revision and the query needs to always fetch all the rows with the highest revision number. Is this possible with a single query?

I realize I could change the database design, by adding a third table called offer_revision, I could join this table with a select condition to fetch the latest revision number and then connect this table to the rows. This however would take considerable refactoring so I only want to do it if I have to.

I also want to do this with a direct query - no stored procedures.

Of course it is possible:

SELECT o.*, r.revision, r.something_else
FROM offer o,
     offer_rows r
WHERE o.offer_id = r.offer_id
  AND r.revision = (
    SELECT max(revision)
    FROM offer_rows
    WHERE offer_id = o.offer_id
  ) 

You can select all the rows from offer_rows with the MAX(revision) and then JOIN the offer table (no nested query will be required):

SELECT *, MAX(revision) as latest_revision
FROM offer_rows or
INNER JOIN offer o USING( offer_id )
GROUP BY offer_id

Yes this is possible with a single query. You could have a subquery that get's the highest revision in the WHERE clause.

I've used the following comparison to get a latest version entry:

AND `outer`.`version` = (
    SELECT MAX( `inner`.`version` )
    FROM `content` `inner`
    WHERE `inner`.`id` = `outer`.`id`
    AND `inner`.`language` = `outer`.`language`
)

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