我对SQL缺乏经验,我不确定如何正确地构建此查询。
Select comment.text, (COUNT(parent.id)-1) AS depth
FROM comments AS comment,
comments AS parent
WHERE comment.lft BETWEEN parent.lft AND
parent.rght LEFT JOIN users as user ON (comment.user_id = user.id)
GROUP BY comment.id ORDER BY comment.lft
我正在尝试检索存储在MySQL数据库中的嵌套用户注释。除了每个注释,我还试图通过JOIN检索注释的关联用户,但我不确定这样的语法是什么。
答案 0 :(得分:1)
WHERE子句后不能有连接。试试这个:
SELECT comment.text, (COUNT(parent.id)-1) AS depth
FROM comments AS comment
JOIN comments AS parent
ON comment.lft BETWEEN parent.lft AND parent.rght
LEFT JOIN users as user
ON comment.user_id = user.id
GROUP BY comment.id ORDER BY comment.lft
也可能是您已加入用户表以选择发布评论的用户的用户名?然后你也需要选择那一列。将user.username添加为select语句中的额外列,您将得到如下结果:
'ELECTRONICS', 0, 'Foo'
'TELEVISIONS', 1, 'Foo'
'TUBE', 2, 'Foo'
'LCD', 2, 'Bar'
'PLASMA', 2, 'Foo'
'PORTABLE ELECTRONICS', 1, 'Bar'
'MP3 PLAYERS', 2, 'Foo'
'FLASH', 3, 'Foo'
'CD PLAYERS', 2, 'Foo'
'2 WAY RADIOS', 2, 'Foo'
用于测试此测试的数据(从here修改):
CREATE TABLE comments (id INT NOT NULL, user_id INT NOT NULL, text NVARCHAR(100) NOT NULL, lft INT NOT NULL, rght INT NOT NULL);
INSERT INTO comments (id, user_id, text, lft, rght) VALUES
(1, 1, 'ELECTRONICS', 1, 20),
(2, 1, 'TELEVISIONS', 2, 9),
(3, 1, 'TUBE', 3, 4),
(4, 2, 'LCD', 5, 6),
(5, 1, 'PLASMA', 7, 8),
(6, 2, 'PORTABLE ELECTRONICS', 10, 19),
(7, 1, 'MP3 PLAYERS', 11, 14),
(8, 1, 'FLASH', 12, 13),
(9, 1, 'CD PLAYERS', 15, 16),
(10, 1, '2 WAY RADIOS', 17, 18);
CREATE TABLE Users (id INT NOT NULL, username NVARCHAR(100) NOT NULL);
INSERT INTO Users (id, username) VALUES
(1, 'Foo'),
(2, 'Bar');