我正在使用类别的嵌套集。我理解查找深度和叶节点等的基本原理。
我正在制作的网站是多语言的,因此需要根据用户选择的语言显示类别名称。网址是不变的。
简化表格如下......
分类
+----+-----+-----+-------------------------+
| id | lft | rgt | url |
+----+-----+-----+-------------------------+
| 1 | 1 | 12 | top_level |
| 2 | 2 | 5 | foo |
| 3 | 3 | 4 | foo_sub_cat |
| 4 | 6 | 11 | bar |
| 5 | 7 | 8 | bar_sub_cat_1 |
| 6 | 9 | 10 | bar_sub_cat_2 |
+----+-----+-----+-------------------------+
Category_Info:
+-------------+---------+----------------------------+
| category_id | lang_id | name |
+-------------+---------+----------------------------+
| 1 | 1 | One cat to rule them all |
| 2 | 1 | Foo Cat |
| 3 | 1 | Subcategory of Foo |
| 4 | 1 | Bar Cat |
| 5 | 1 | Bar SubCat |
| 6 | 1 | Another Bar SubCat |
+-------------+---------+----------------------------+
我运行的查询是这样的......
SELECT node.*,
category_info.name,
( Count(parent.url) - 1 ) AS depth
FROM categories AS node,
categories AS parent
JOIN category_info
ON parent.id = category_info.category_id
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND category_info.lang_id = 1
GROUP BY node.url
ORDER BY node.lft
在上面的示例中,返回的是每个结果的名称One cat to rule them all
。这是你所期望的,因为我匹配了parent.id。
JOIN正在杀死我。如果我尝试JOIN node.id = category_info.category_id
,那么我会收到错误告诉我找不到node.id,就像我使用JOIN categories.id = category_info.category_id
一样。
我知道我必须亲近,但我真的无法理解。
答案 0 :(得分:0)
SELECT node.*, category_info.name, (COUNT(parent.url) - 1) AS depth
FROM categories AS node INNER JOIN
^^^^^^^^^^^ <= this is added
categories AS parent
JOIN category_info ON node.id = category_info.category_id
WHERE node.lft BETWEEN parent.lft AND parent.rgt AND category_info.lang_id = 1
GROUP BY node.url
ORDER BY node.lft
如果缺少JOIN
,则无法在ON
子句中引用该列,但可以在WHERE
部分
这是我尝试过的。
mysql> SELECT * FROM t1 tab1 INNER JOIN t1 tab2 INNER JOIN t2 tab3 ON tab1.a = tab3.a;
Empty set (0.00 sec)
mysql> SELECT * FROM t1 tab1, t1 tab2 INNER JOIN t2 tab3 ON tab1.a = tab3.a;
ERROR 1054 (42S22): Unknown column 'tab1.a' in 'on clause