Jump to content
New Reality: Ads For Members ×

Two table query


TapeGun007

Recommended Posts

I’ve used SQL for years, but only very simple one table queries.

 

I have two tables Prospect and Notes:

 

Prospects

                ProspectID

                ProspectName

                ProspectCode

                ProspectStatus

                …

 

Notes

                NoteID

                NoteProspectID

                Note

 

Here is what I want, but I don’t know how to write it in MySQL

 

All prospects with the following

ProspectCode = “123abc”

ProspectStatus = “Contacted”

 

I also want only the last Note from Notes where ProspectID = NoteProspectID.

 

I hope this makes sense.

  

Link to comment
https://forums.phpfreaks.com/topic/298001-two-table-query/
Share on other sites

Barand may come up with something more efficient. But, give this a try:

 

 

SELECT p.ProspectID, p.ProspectName, p.ProspectCode, p.ProspectStatus,
       n.NoteID, n.Note
 
FROM Prospects p
LEFT JOIN Notes n
  ON p.ProspectID = n.NoteProspectID
  AND n.NoteID IN ( SELECT MAX(NoteID) FROM Notes GROUP BY NoteProspectID )
 
WHERE p.ProspectCode = “123abc”
  AND p.ProspectStatus = “Contacted”
Link to comment
https://forums.phpfreaks.com/topic/298001-two-table-query/#findComment-1520035
Share on other sites

 

Barand may come up with something more efficient. But, give this a try:

 

 

Challenge declined :)

 

One comment I would make is that it would be better to put a timestamp in the notes tables to identify the latest rather than relying on id sequence. (Treat ids purely as unique row identities used for internal relationships. A database should function the same if ids were allocated randomly instead of sequentially)

Link to comment
https://forums.phpfreaks.com/topic/298001-two-table-query/#findComment-1520040
Share on other sites

Archived

This topic is now archived and is closed to further replies.



×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.