This is my Mysql Database
╔════╦═══════════╗
║ ID ║ Parent_ID ║
╠════╬═══════════╣
║ 1 ║ 0 ║
╠════╬═══════════╣
║ 2 ║ 1 ║
╠════╬═══════════╣
║ 3 ║ 1 ║
╠════╬═══════════╣
║ 4 ║ 3 ║
╠════╬═══════════╣
║ 5 ║ 4 ║
╚════╩═══════════╝
What I want to achieve :
When user search for ID 1 , I want to get all those element whose Parent_ID is 1 and also all those IDs whose have 1 as their parent or grand parent or great grand parent and so on.
OR Simply all descendants of ID 1.
Example :
if user search for 1, the algorithm should give result
{2,3,4,5} -- 4,5 because 1 is their great grand parent.if user search for 2, the algorithm should give empty result { } as no element have 2 as a Parent_ID
if user search for 3, the algorithm should give result {4,5} -- 5 because 3 is its grand parent.
What is the good way of saving and retrieving these type of data from database?
I am using Java and MySQL.
Thanks.