0

这是我的查询

     $query="SELECT parent.name, parent.depth
        FROM  address AS node,
                address AS parent
        WHERE node.name LIKE '%".$name."%' AND   
        node.lft BETWEEN parent.lft AND parent.rgt   
        order by node.lft, parent.rgt";

这是我的表结构:

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

让我们假设$name=k 那么结果将是

name        |depth|
------------+-----+
kingsford   | 4   |
sydney      | 3   | 
nsw         | 2   | 
Australia   | 1   |
kensington  | 4   | 
sydney      | 3   | 
nsw         | 2   | 
Australia   | 1   |

我将这样介绍它们:

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

我不能将其限制为最多仅涵盖 10 个地址。例如,如果我添加limit 2它不会显示上面的两个地址。它只会显示这个-->kensington, sydney。我怎样才能做到这一点?

4

1 回答 1

0

也许这个问题不太清楚,但如果我理解正确,我会使用这样的东西:

SELECT
  GROUP_CONCAT(parent.name ORDER BY parent.depth DESC) AS name
FROM
  address AS node JOIN address AS parent
  ON node.lft BETWEEN parent.lft AND parent.rgt  
WHERE node.name LIKE '%k%'
GROUP BY node.name
LIMIT 10

在此处查看小提琴。

编辑

您可能还想使用它,它以原始格式返回行:

SELECT
  parent.name, parent.depth
FROM
  (SELECT name, lft FROM address WHERE name LIKE '%k%' LIMIT 10) AS node,
  address AS parent
WHERE
  node.lft BETWEEN parent.lft AND parent.rgt   
order by node.lft, parent.rgt
于 2013-04-06T14:04:12.897 回答