Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I join the most recent row in one table to another table?
    primarykey
    data
    text
    <p>I have data that looks like this:</p> <pre><code>entities id name 1 Apple 2 Orange 3 Banana </code></pre> <p>Periodically, a process will run and give a score to each entity. The process generates the data and adds it to a scores table like so:</p> <pre><code>scores id entity_id score date_added 1 1 10 1/2/09 2 2 10 1/2/09 3 1 15 1/3/09 4 2 10 1/03/09 5 1 15 1/4/09 6 2 15 1/4/09 7 3 22 1/4/09 </code></pre> <p>I want to be able to select all of the entities along with the most recent recorded score for each resulting in some data like this:</p> <pre><code>entities id name score date_added 1 Apple 15 1/4/09 2 Orange 15 1/4/09 3 Banana 15 1/4/09 </code></pre> <p>I can get the data for a single entity using this query:</p> <pre><code>SELECT entities.*, scores.score, scores.date_added FROM entities INNER JOIN scores ON entities.id = scores.entity_id WHERE entities.id = ? ORDER BY scores.date_added DESC LIMIT 1 </code></pre> <p>But I'm at a loss for how to select the same for all entities. Perhaps it's staring me in the face?</p> <p>Thank you very kindly for taking the time.</p> <p>Thanks for the great responses. I'll give it a few days to see if a preferred solution bubbles up then I'll select the answer.</p> <p>UPDATE: I've tried out several of the proposed solutions, the main issue I'm facing now is that if an entity does not yet have a generated score they don't appear in the list. </p> <p>What would the SQL look like to ensure that all entities are returned, even if they don't have any score posted yet?</p> <p>UPDATE: Answer selected. Thanks everyone!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload