MySQL database banner

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)
tagName (varchar)
tagParent (int)

tblTags is populated with data as follows:

1Food& Beverage0
3Parking Areas0
4Bar Area1
5Restaurant Area1
6Pool Area1

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!

By foxbeefly

PHP / MySQL Developer. HTML, CSS and some JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.