查询设计问题

时间:2013-04-05 14:48:01

标签: mysql

我在此表address中有一个嵌套列表:

name        |lft | rgt |
------------+----+-----+
Australia   | 1  | 10  |
nsw         | 2  | 9   |
sydney      | 3  | 8   |
kensington  | 4  | 5   |
kingsford   | 6  | 7   |
------------+----+-----+

表格说明:正如您所看到的,澳大利亚从左右两侧包含了其下的所有其他数据。这同样适用于nsw和sydney,它们包含了它们之下的内容。肯辛顿和金斯福德有相同的深度,他们属于悉尼。

我正在尝试为自动完成搜索编写查询。我想在输入'k'时得到这些结果:

-->kensington, sydney, nsw, australia
-->kingsford, sydney, nsw, australia

当前查询:

   'SELECT parent.name
        FROM  address AS node,
                address AS parent
        WHERE node.lft BETWEEN parent.lft AND parent.rgt
                AND node.name LIKE ' . $input

我所拥有的查询确实返回相同的值,但“混淆”如下:

    Array
    (
        [0] => australia
        [name_en] => australia
    )
    Array
    (
        [0] => australia
        [name_en] => australia
    )
    Array
    (
        [0] => NSW
        [name_en] => NSW
    )
    Array
    (
        [0] => NSW
        [name_en] => NSW
    )
    Array
    (
        [0] => sydney
        [name_en] => sydney
    )
    Array
    (
        [0] => sydney
        [name_en] => sydney
    )
    Array
    (
        [0] => kensington
        [name_en] => kensington
    )
    Array
    (
        [0] => kingsford
        [name_en] => kingsford
    )

我寻求的结果就是这个

    Array
    (
        [0] => australia
        [name_en] => australia
    )
    Array
    (
        [0] => NSW
        [name_en] => NSW
    )
    Array
    (
        [0] => sydney
        [name_en] => sydney
    )
    Array
    (
        [0] => kensington
        [name_en] => kensington
    )
    Array
    (
        [0] => australia
        [name_en] => australia
    )
    Array
    (
        [0] => NSW
        [name_en] => NSW
    )
    Array
    (
        [0] => sydney
        [name_en] => sydney
    )
    Array
    (
        [0] => kingsford
        [name_en] => kingsford
    )

它应该一个接一个地返回路径。

http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT parent.name
    FROM  address_tmp AS node,
            address_tmp AS parent
    WHERE node.lft BETWEEN parent.lft AND parent.rgt
            AND node.name LIKE 'k%' order by node.lft, node.rgt, parent.rgt

(我用k作为查询的例子)