Sql – return latest version of a drupal node

drupaldrupal-6sql

I'm writing a drupal module, and I need to write a query that returns particular rows of one of my content_type tables. My query so far is:

SELECT DISTINCT pb.*, f.filepath FROM {content_type_promo_box} pb LEFT JOIN {files} f ON pb.field_promo_image_fid = f.fid

I realized as I was working that the table not only contains each cck field of this content type, it also contains multiple versions for each field. How do I limit my query to the rows that only contain values for the current versions of the nodes?

UPDATE: I need to clarify my question a little. I've been down the views path already, and I did think about using node_load (thanks for the answer, though, Jeremy!). Really, my question is more about how to write an appropriate SQL statement than it is about drupal specifically. I only want to return rows that contain the latest versions (vid is the greatest) for any particular node (nid). So here's an example:

-------------
| nid | vid |
-------------
| 45  |  3  |
| 23  |  5  |
| 45  |  9  |
| 23  |  12 |
| 45  |  36 |
| 33  |  44 |
| 33  |  78 |
------------- 

My query should return the following:

-------------
| nid | vid |
-------------
| 23  |  12 |
| 45  |  36 |
| 33  |  78 |
-------------

Make sense? Thanks!

Best Answer

Assuming that (nid, vid) combination is unqiue:

SELECT  m.*
FROM    (
        SELECT  nid, MAX(vid) AS mvid
        FROM    mytable
        GROUP BY
                nid
        ) q
JOIN    mytable m
ON      (m.nid, m.vid) = (q.nid, q.mvid)
Related Topic