MySQL - 仅获取特定父级的子级

时间:2014-12-22 12:49:29

标签: mysql sql

如果我运行以下查询:

SELECT loc2.* FROM `locations` AS loc
INNER JOIN `locations` AS loc2 ON loc.location_id = loc2.location_parent
WHERE loc.location_status='publish'

我得到以下结果:

+-------------+------------------+-----------------+-----------------+
| location_id | location_name    | location_parent | location_status |
+-------------+------------------+-----------------+-----------------+
|          19 | Dhaka Division   |             564 | publish         |
|          22 | Dhaka District   |              19 | publish         |
|          26 | Dhaka City       |              22 | publish         |
|          28 | Mirpur           |              26 | publish         |
|          30 | Mirpur - 12      |              28 | publish         |
|          32 | Mirpur DOHS      |              30 | publish         |
|         634 | Gazipur District |              19 | publish         |
+-------------+------------------+-----------------+-----------------+
7 rows in set (0.00 sec)

实际上我正在尝试从数据库中获取所有孩子/孙子女。现在,上面的查询只是根据父子规则对行进行排序并返回所有行。但是,我想为SQL添加一个条件,以便它只获取特定父级的子级。

例如,我想获取19的所有子行/节点/位置。结果集应如下:

+-------------+------------------+-----------------+-----------------+
| location_id | location_name    | location_parent | location_status |
+-------------+------------------+-----------------+-----------------+
|          22 | Dhaka District   |              19 | publish         |
|          26 | Dhaka City       |              22 | publish         |
|          28 | Mirpur           |              26 | publish         |
|          30 | Mirpur - 12      |              28 | publish         |
|          32 | Mirpur DOHS      |              30 | publish         |
+-------------+------------------+-----------------+-----------------+

我试过这个:

SELECT loc2.* FROM `locations` AS loc
INNER JOIN `locations` AS loc2 ON loc.location_id = loc2.location_parent
WHERE loc.location_status='publish' AND loc2.location_parent=19

和此:

SELECT loc2.* FROM `locations` AS loc
INNER JOIN `locations` AS loc2 ON loc.location_id = loc2.location_parent
WHERE loc.location_status='publish' AND loc.location_parent=19

但他们都应该返回相同的结果:

+-------------+------------------+-----------------+-----------------+
| location_id | location_name    | location_parent | location_status |
+-------------+------------------+-----------------+-----------------+
|          22 | Dhaka District   |              19 | publish         |
+-------------+------------------+-----------------+-----------------+

那么,我该怎么做才能达到我需要的效果呢?

2 个答案:

答案 0 :(得分:0)

实际上,这是一个称为递归的数据库的高级主题,您的要求是从最顶层的父级及其所有子级,孙子级等获取数据树。

其他DBMS提供了解决此类问题的功能,例如Microsoft SQL Server调用其解决方案CTE(Common Table Express),但是这在mySQL中很长,并且没有简单的解决方案来解决您的问题。但是,您可以在mysql中搜索递归以获取有关此主题的更多详细信息。

答案 1 :(得分:0)

您正在寻找的是"关闭"表。这本质上是一个表,用于保持分层数据的子,父和深度的引用。

我在这里发现了一篇很棒的帖子,可以帮助你达到理想的效果。 What are the options for storing hierarchical data in a relational database?