I have blogged before about simplicity in code: how the simplest solutions are usually the best, and I normally put it down to elegance.
I have the following table:
tagID (int, PK)
tblTags is populated with data as follows:
Tags 4, 5, and 6 are obviously child tags of parent tag 1.
I now needed a list of names of Parent Tags – but only if they had children – in other words, I am looking for Tag 1: Food and Beverage.
My colleague suggested running two queries: the first to get an array from a list of tagID’s appearing in the tagParent column, and the second to then get the tagID’s and tagNames of the Tags whose tagID’s are in that array.
He couldn’t understand why I spent some time looking for a better solution, coming up with:
SELECT tagID, tagName FROM tblTags WHERE tagID IN (SELECT DISTINCT tagParent FROM tblTags)
It’s simply more elegant!