The earliest version of this rhyme is given in History of Middle-earth 6, in the chapter entitled "Arrival at Bree", and there it's noted that it was originally published in 1923 in Yorkshire Poetry Volume II no 19. The original title that Tolkien gave it is worth quoting:
THE CAT AND THE FIDDLE
or
A Nursery Rhyme Undone and its Scandalous Secret Unlocked
This version is different to that published in Fellowship of the Ring, but there is a clear lineage with several points of similarity and even identical wording:
- It takes place in an inn "beneath an old grey hill".
- The ostler and his cat appear in it.
- As do the dog who likes jokes and the cow who gets drunk on music.
- The spoon is specifically identified as being a "Sunday spoon".
- The Man in the Moon gets quite drunk indeed.
- Etc.
Christopher Tolkien mentions two subsequent versions which move towards the final form, with this being virtually attained by way of amendments to the second, although he does not give these intermediate texts.
It's therefore quite clear (and the title alone gives that away) that it was Tolkien's explicit intention when he originally wrote the rhyme that it should serve as a "background story" or "original version" for the more familiar nursery rhyme of today. Subsequent revision and reuse then saw it make it's appearance in Lord of the Rings.