Here is stackoverflow question that seems to refer to your problem https://stackoverflow.com/questions/39555616/detect-cycles-using-sql
Here is stackoverflow question that seems to refer to your problem https://stackoverflow.com/questions/39555616/detect-cycles-using-sql