表别名+左连接

时间:2013-11-10 09:24:38

标签: php mysql nested-sets

所以,我正在尝试实现嵌套集模型,我有以下查询

SELECT 
    n.CategoryID, 
    CategoriesI18n.CategoryName, 
    COUNT(*)-1 AS level FROM Categories AS n, 
    Categories AS p LEFT JOIN CategoriesI18n ON (
        n.CategoryID=CategoriesI18n.CategoryID AND CategoriesI18n.Locale="en-US"
    ) WHERE n.lft BETWEEN p.lft AND p.rgt GROUP BY n.lft ORDER BY n.lft;

当我选择树时,我必须加入CategoriesI18n表,这是当前类别的多语言行。但是我得到了这个错误

Unknown column 'n.CategoryID' in 'on clause'

我不知道为什么。也许类别AS p会覆盖第一个别名?

2 个答案:

答案 0 :(得分:2)

没关系我弄清楚了。不得不做嵌套选择。

SELECT n.CategoryID, n.CategoryName, COUNT(*)-1 AS level 
    FROM (
        SELECT Categories.CategoryID AS CategoryID,  Categories.lft AS lft,  Categories.rgt AS rgt, CategoriesI18n.CategoryName AS CategoryName FROM Categories LEFT JOIN CategoriesI18n ON (Categories.CategoryID=CategoriesI18n.CategoryID AND CategoriesI18n.Locale="bg-BG")
        ) AS n, Categories AS p 
    WHERE n.lft BETWEEN p.lft AND p.rgt GROUP BY n.lft ORDER BY n.lft;

答案 1 :(得分:0)

'Categories AS p LEFT JOIN CategoriesI18n',加入的Categories的别名是'p',而不是'n'