


Finding Parents in a MySQL Table with Recursion
In a database schema, establishing hierarchical relationships is common. When querying such data, it becomes necessary to retrieve not only specific records but also their hierarchical connections. This article will address the task of finding all parents of a record within a MySQL table using a single query.
Problem Statement
Given a table with columns ID, TITLE, CONTROLLER, METHOD, and PARENT_ID, find all the parents of a record where the TITLE is "Categories" using a single SQL query.
Desired Output
The output should display the following columns:
- id
- title
- controller
- method
- url
- parent_id
and should fetch the records:
id | title | controller | method | url | parent_id |
---|---|---|---|---|---|
3 | Modules | admin | modules | (NULL) | 0 |
17 | User Modules | modules | user_module | (NULL) | 3 |
31 | Categories | categories | category | (NULL) | 17 |
Solution
To achieve the desired output, we need to leverage MySQL's recursive query capabilities. Here's the SQL query we can use:
SELECT T2.id, T2.title,T2.controller,T2.method,T2.url FROM ( SELECT @r AS _id, (SELECT @r := parent_id FROM menu WHERE id = _id) AS parent_id, @l := @l + 1 AS lvl FROM (SELECT @r := 31, @l := 0) vars, menu m WHERE @r 0) T1 JOIN menu T2 ON T1._id = T2.id ORDER BY T1.lvl DESC;
Let's break down this query:
- The inner query (SELECT @r AS _id, ...) generates a hierarchy of records by recursively selecting the PARENT_ID and incrementing the level.
- The outer query (SELECT T2.id, ...) joins the inner query with the original table menu (renamed to T2) to obtain the desired data.
- The ORDER BY clause sorts the results by level in descending order.
By executing this query, we can retrieve all the parents of the record with TITLE as "Categories" in a single database call.
The above is the detailed content of How Can I Find All Parent Records in a MySQL Table Using a Single Recursive Query?. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

Article discusses using foreign keys to represent relationships in databases, focusing on best practices, data integrity, and common pitfalls to avoid.

The article discusses creating indexes on JSON columns in various databases like PostgreSQL, MySQL, and MongoDB to enhance query performance. It explains the syntax and benefits of indexing specific JSON paths, and lists supported database systems.

Article discusses securing MySQL against SQL injection and brute-force attacks using prepared statements, input validation, and strong password policies.(159 characters)


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version