Hello!
Say I have the following tables:
Pets
=====
id - integer (pk)
name - varchar
type - varchar
notes
=====
id - integer (pk)
pet_id - integer (fk)
note_text - text
date - date/time
I'd like to query for pets of type "dog", and I'd like the query to also return the most recent note associated with that pet, if any.
Here's an example:
Pets (id|name|type)
====
1|Fluffy|cat
2|Sammy|dog
3|Ralph|dog
4|Cheeky|dog
notes (id|pet_id|text|date)
=====
1|2|'sammy is healthy'|'2001-08-02'
2|2|'came to the office'|'2003-01-01'
3|4|'saw at lunch'|'2005-01-01'
I want a query that basically says, "Select all dogs and the most recent notes associated with each dog if any."
The results I'm looking for are:
name|notes|date
================
Sammy|'came to the office'|'2003-01-01'
Ralph|NULL|NULL
Cheeky|'saw at lunch'|'2005-01-01'
Any ideas on what this query would look like? I need something that would work for both sql server and mysql.
Thanks!
- Bret
Say I have the following tables:
Pets
=====
id - integer (pk)
name - varchar
type - varchar
notes
=====
id - integer (pk)
pet_id - integer (fk)
note_text - text
date - date/time
I'd like to query for pets of type "dog", and I'd like the query to also return the most recent note associated with that pet, if any.
Here's an example:
Pets (id|name|type)
====
1|Fluffy|cat
2|Sammy|dog
3|Ralph|dog
4|Cheeky|dog
notes (id|pet_id|text|date)
=====
1|2|'sammy is healthy'|'2001-08-02'
2|2|'came to the office'|'2003-01-01'
3|4|'saw at lunch'|'2005-01-01'
I want a query that basically says, "Select all dogs and the most recent notes associated with each dog if any."
The results I'm looking for are:
name|notes|date
================
Sammy|'came to the office'|'2003-01-01'
Ralph|NULL|NULL
Cheeky|'saw at lunch'|'2005-01-01'
Any ideas on what this query would look like? I need something that would work for both sql server and mysql.
Thanks!
- Bret