鉴于数据库.....
ID Name item_order Manager
1 ted 2 N
2 bob 5 N
3 tony 1 Y
4 fred 3 N
5 william 4 N
6 george 6 Y
7 cade 8 N
8 matt 7 N
我希望能够在当前非经理名称之前选择经理Id。因此,例如bob的结果将是tony或3。
我可以通过两个请求找出如何做到这一点
SELECT MAX( item_order) AS parent
FROM tablename WHERE item_order < 5 && Manager = 'Y'
结果我将通过item_order进行另一次选择。有没有办法在一个选择中完成所有这些?
答案 0 :(得分:0)
SELECT
n.*,
ManagerName = m.Name
FROM tablename n
LEFT JOIN tablename m ON m.Manager = 'Y' AND n.item_order > m.item_order
LEFT JOIN tablename m2 ON m2.Manager = 'Y'
AND m2.item_order < n.item_order AND m2.item_order > m.Item_order
WHERE n.Manager = 'N'
AND m2.ID IS NULL
这将为您提供所有非经理的列表以及直接位于他们之前的经理的姓名(基于item_order
)。
如果您只想为特定的非经理人返回一行,请再添加一个条件:
AND n.Name = 'bob'
答案 1 :(得分:0)
SELECT * FROM tablename
WHERE Manager = 'Y'
AND item_order = (SELECT MAX(item_order) AS parent
FROM tablename
WHERE item_order < 5
AND Manager = 'Y') AS t