简体   繁体   中英

find relations in mysql

i have two tables in my database that store my data and their categories.my data table has one important column that specifies its last category and each category in category table has a parent category that points to a parent category and root categories parent_id is '0'

like this: 在此处输入图片说明

now the 'data' table row points to a row in 'categories' table that has id of '7' and it's LED that its parent id is '3' and '3' is Monitor that its parent id is '2' and '2' is Computer Accessories that its parent id is '1' and '1' is Digital stuff and it's one of roots because its parent id is 0

now if i want to find all of data that has been related to the digital stuff or computer accessories with a simple sql query what can i do ? or do you have a better solution to store my data and categories?

in your query first of fall you decide which level you want to show the hierarchy

SELECT a.id, d.name, a.title, b.title as parent_title_name
FROM data d JOIN categories a
ON d.category_id = a.id
JOIN categories b
ON a.id = b.parent_id;

in this query you show the data, its category and it's perent category

With the help of PHP you can do that by recursive function to get all categories and than a query to get data.

$host = 'localhost';
$username = 'root';
$password = 'root';
$database = 'test';
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

function getCategories($id, $conn, &$ids=[]) {
    $ids[] = $id;
    $sql = "SELECT parent_id FROM categories WHERE id= $id";
    $result = $conn->query($sql);
    while ($row = $result->fetch_assoc()) {
        $parent_id = $row['parent_id'];
        if ($parent_id) {
            return getCategories($parent_id, $conn, $ids);
        }
    }
    return $ids;
}

$ids = implode(',', getCategories(7));
$sql = "SELECT * FROM data WHERE category_id in ($ids)";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
    print_r($row);
}

And if you want to do that using mysql than i guess you've to create procedure for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM