我在 Mysql 中看到了一个关于分层数据的页面,它回答了我 50% 的问题。这是链接。现在,要抛出嵌套模型,我希望我也可以为嵌套表上的每条记录加入其他表。例如,我将数据存储在包含产品详细信息的嵌套模型层次结构中。现在,我希望我能看到哪个用户购买了哪个产品,并从中获取用户详细信息。
为此,我添加了一个名为表的字段user_id
,nested_category
其中包含表user_id
的user_info
。我想首先检查用户表(检测登录的人),然后想获取他拥有哪些产品的详细信息。
为此,我正在使用此查询-
SELECT node.name, node.category_id, node.comment, node.user_id, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM nested_category AS node,
nested_category AS parent,
nested_category AS sub_parent,
user_info,
(
SELECT node.name, (COUNT(parent.name) - 1) AS depth
FROM nested_category AS node,
nested_category AS parent,
user_info
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.user_id = user_info.user_id AND user_info.user_id = 1
GROUP BY node.name
ORDER BY node.lft
)AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.name = sub_tree.name
GROUP BY node.name
ORDER BY node.lft;
但是这个查询不能正常运行(我的意思是说查询正在运行但deails不是分层方式)。谁能帮我?
编辑:
我尝试过修改代码,现在代码是 -
SELECT node.name, node.category_id, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM nested_category AS node,
nested_category AS parent,
nested_category AS sub_parent
(
SELECT node.name, (COUNT(parent.name) - 1) AS depth
FROM nested_category AS node,
nested_category AS parent,
LEFT JOIN user_info ON user_info.user_id = node.user_id
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND user_info.user_id = 1
GROUP BY node.name
ORDER BY node.lft
)AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.name = sub_tree.name
GROUP BY node.name
ORDER BY node.lft;
现在产生的结果是这样的 -
现在需要考虑以下事项-
- category_id 上的按钮效果(WHY?)
- 即使我现在使用 user_id 来产生输出,深度的计算也是错误的。
请解释。