我在表tbl
中有以下列:
OrderID: Parent: Child:
1 1 1
2 2 1
3 1 2
4 1 1
5 2 1
我想获得当前(OrderID
,Parent
,Child
)和LOWER (OrderID,Parent,Child)
WHERE父级和子级等于当前OrderID的父级和子级。< / p>
因此,例如,如果我对OrderID=4
有查询,则结果应为:
OrderID: Parent: Child:
4 1 1
1 1 1
和if OrderID=5
OrderID: Parent: Child:
5 2 1
2 2 1
顺便说一下,我可以用PHP做到这一点,但我想在一个查询中完成。
答案 0 :(得分:0)
这样可以解决问题:
SELECT *
FROM tbl
WHERE Parent = (SELECT Parent FROM tbl WHERE OrderID = 4)
AND Child = (SELECT Child FROM tbl WHERE OrderID = 4)
在php中将行提取到一个数组中,搜索你的OrderID并获取它之前的那个。
答案 1 :(得分:0)
SELECT * FROM FROM Orders WHERE OrderID = 4
UNION ALL
SELECT * FROM FROM Orders WHERE Parent = 4 ORDER BY OrderID DESC Limit 1
另外,如果你有时间看看我的答案会给你一个很好的演示。
答案 2 :(得分:0)
SELECT * FROM FROM Orders WHERE OrderID = @orderId
UNION ALL
SELECT * FROM FROM Orders WHERE Parent = @orderId
答案 3 :(得分:0)
你可以这样做:
(SELECT OrderID, Parent, Child
FROM tbl
WHERE OrderID = 4)
UNION
(SELECT OrderID, Parent, Child
FROM tbl
WHERE Parent = (SELECT Parent FROM tbl WHERE OrderID = 4)
AND Child = (SELECT Child FROM tbl WHERE OrderID = 4)
ORDER BY OrderID ASC LIMIT 1)
我不确定这个的表现虽然......
答案 4 :(得分:0)
这适合我。
select B.* from
(select A.Parent,A.Child from `tbl` A
where A.OrderID = 4) C
inner join `tbl` B
on C.Parent = B.Parent
and C.Child = B.Child
order by B.OrderID desc
答案 5 :(得分:0)
好的,感谢所有回复,但我得到了自己的回答。
SELECT a.OrderID,a.Parent,a.Child FROM tbl a
JOIN (SELECT OrderID,Parent,Child FROM tbl WHERE OrderID={$OrderID}) b
ON a.Parent=b.Parent
AND a.Child=b.Child
WHERE a.OrderId<=b.OrderID
ORDER BY OrderID
DESC LIMIT 2