【问题标题】:find relations in mysql在mysql中查找关系
【发布时间】:2016-07-02 07:01:22
【问题描述】:

我的数据库中有两个表来存储我的数据及其类别。我的数据表有一个重要的列指定它的最后一个类别,类别表中的每个类别都有一个指向父类别的父类别和根类别 parent_id是“0”

像这样:

现在'data'表行指向'categories'表中id为'7'的行,其父id为'3'的LED和'3'是Monitor,其父id为'2 ' 和 '2' 是 Computer Accessories,它的父 id 是 '1' 而 '1' 是 Digital stuff,它是根之一,因为它的父 id 是 0

现在,如果我想通过简单的 sql 查询来查找与数字产品或计算机配件相关的所有数据,我该怎么办?还是您有更好的解决方案来存储我的数据和类别?

【问题讨论】:

标签: php mysql database database-design


【解决方案1】:

首先在您的查询中决定要显示层次结构的级别

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;

在此查询中,您将显示数据、其类别及其相关类别

【讨论】:

【解决方案2】:

在 PHP 的帮助下,您可以通过递归函数来获取所有类别,而不是通过查询来获取数据。

$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);
}

如果你想使用 mysql 来做到这一点,我猜你必须为此创建程序。

【讨论】:

    猜你喜欢
    • 2010-10-07
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多