具有id列的GROUP BY parent_id列

时间:2014-09-27 15:59:31

标签: mysql sql

我有我的域名表。

+-----------+-----------+
| domain_id | parent_id |
+-----------+-----------+
|        12 |      NULL |
|        14 |      NULL |
|        13 |        12 |
|        15 |        14 |
|        16 |        14 |
|        19 |        14 |
|        18 |        15 |
|        17 |        16 |
+-----------+-----------+

parent_id与domain_id有多对一的关系。但是,当我查询时,我想将所有parent_id分组到正确的域ID下,但我遇到了问题。

1 个答案:

答案 0 :(得分:1)

假设你也有相关的域名并且没有提供它你就可以这样做..但你必须知道要走多少级别......这些级别将由每个左边创建加入

设置:

CREATE TABLE domains (
    id int, 
    parent int, 
    name varchar(255)
); 
INSERT INTO domains VALUES
(12, NULL, "Dell.com"),
(14, NULL, "Sprint.com"),
(13, 12, "Dell.net"),
(15, 14, "Sprint.net"),
(16, 14, "Sprint.edu"),
(19, 14, "TechSprint.com"),
(18, 15, "SupportSprint.net"),
(17, 16, "SupportSprint.edu");

查询:

SELECT 
    d1.name as level1, 
    d2.name as level2, 
    d3.name as level3, 
    d4.name as level4
FROM domains AS d1
LEFT JOIN domains AS d2 ON d2.parent = d1.id
LEFT JOIN domains AS d3 ON d3.parent = d2.id
LEFT JOIN domains AS d4 ON d4.parent = d3.id
WHERE d1.name = "Sprint.com"

结果:

+------------+-------------------+-------------------+--------+
|    NAME    |       LEV2        |       LEV3        |  LEV4  |
+------------+-------------------+-------------------+--------+
| Sprint.com | Sprint.net        | SupportSprint.net | (null) |
| Sprint.com | Sprint.edu        | SupportSprint.edu | (null) |
| Sprint.com | TechSprint.com    | (null)            | (null) |
+------------+-------------------+-------------------+--------+

Fiddle Demo

注意:

此查询中的WHERE是一个过滤器,用于沿着一个域的路径向下移动。如果删除WHERE,那么您将获得所有的路径..但​​是会有很多空值 你还需要知道一个域有多少个孩子......因为你不知道要为孩子们​​做多少次LEFT JOINS