OsakaWebbie
Programmer
I have a table pw_song with song information (primary key autoincrement SongID) and table pw_usage which has SongID, EventID and UseDate (all NotNull fields). A song may or may not have any pw_usage records associated with it. I use PHP to assemble a query from many different dynamic parts to list songs that fit any of a number of criteria unrelated to usage - that has been working fine. Now I'm trying to add functionality to also tell me the last date a song was used for a given event, if any. Without that, the select statement looks something like this (the where clause and even number of tables may vary, but the behavior is the same):
To that, I dynamically add what I thought would just give me the last date used (or null if never used):
With this query sometimes I get fewer records overall than with the first query. Checking my data in just a few example cases, it looks like the records disappear when there are pw_usage records for that song but none for that event; if there are no pw_usage records at all it works fine, and if there is at least one record for the requested event it works fine. That would seem to point to the "(pw_usage.EventID=2 OR ISNULL(pw_usage.EventID))" as the culprit, but I'm not very experienced at trying to do aggregate functions with a many-many relationship table, so I don't know the right way to limit the pw_usage records to a certain EventID but not limit the pw_song records. I tried using HAVING instead of part of the WHERE, but then it complained that EventID was an unknown column. Can someone help?
Code:
SELECT pw_song.SongID,Title,Tagged,OrigTitle,Tempo,SongKey,LEFT(Lyrics,INSTR(Lyrics,' ')-1) AS FirstLine FROM pw_song WHERE Title LIKE '%praise%' OR OrigTitle LIKE '%praise%' ORDER BY OrigTitle
To that, I dynamically add what I thought would just give me the last date used (or null if never used):
Code:
SELECT pw_song.SongID,Title,Tagged,OrigTitle,Tempo,SongKey,LEFT(Lyrics,INSTR(Lyrics,' ')-1) AS FirstLine,MAX(pw_usage.UseDate) AS Last FROM pw_song LEFT JOIN pw_usage ON pw_song.SongID=pw_usage.SongID WHERE Title LIKE '%praise%' OR OrigTitle LIKE '%praise%' AND (pw_usage.EventID=2 OR ISNULL(pw_usage.EventID)) GROUP BY pw_song.SongID ORDER BY OrigTitle