我有一个像这样的SQL查询 -
select * from (SELECT parent.item_name as name, parent.lft as lft
FROM item_tree AS item,
item_tree AS parent
WHERE item.lft > parent.lft AND item.rgt < parent.rgt
AND item.item_id = 6)
as ABC
这会返回一个表 -
name | lft
A | 1
B | 2
C | 3
但是,我需要值C,因为它具有最大lft值。 所以,我修改了下面的代码 -
select * from (SELECT parent.item_name as name, parent.lft as lft
FROM item_tree AS item,
item_tree AS parent
WHERE item.lft > parent.lft AND item.rgt < parent.rgt
AND item.item_id = 6)
as ABC
having ABC.lft = MAX(ABC.lft)
现在,此查询不返回任何值。 这段代码有什么问题?
提前致谢!
答案 0 :(得分:1)
尝试此查询
SELECT name, lft
from (SELECT parent.item_name as name, parent.lft as lft
FROM item_tree AS item,
item_tree AS parent
WHERE item.lft > parent.lft AND item.rgt < parent.rgt
AND item.item_id = 6)
as ABC
ORDER BY lft DESC
LIMIT 1
答案 1 :(得分:0)
MAX is agregate function, and not working without GROUP BY.
Try this:
select * from (SELECT parent.item_name as name, parent.lft as lft
FROM item_tree AS item,
item_tree AS parent
WHERE item.lft > parent.lft AND item.rgt < parent.rgt
AND item.item_id = 6)
as ABC
order by ABC.lft desc limit 1