0

我在表中有以下列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 Parent and Child 等于当前 OrderID 的 Parent 和 Child。

因此,例如,如果我查询OrderID=4结果应该如下:

OrderID:  Parent:    Child:
4            1         1
1            1         1

if OrderID=5

OrderID:  Parent:    Child:
5           2           1
2           2           1

顺便说一句,我可以在 PHP 中执行此操作,但我想在单个查询中执行此操作。

4

6 回答 6

0

这可以解决问题:

SELECT *
FROM tbl
WHERE Parent = (SELECT Parent FROM tbl WHERE OrderID = 4) 
    AND Child = (SELECT Child FROM tbl WHERE OrderID = 4) 

并在 php 中将行获取到一个数组中,搜索您的 OrderID 并获取它之前的那个。

于 2012-09-18T10:19:39.137 回答
0
SELECT * FROM FROM Orders WHERE  OrderID = 4
UNION ALL 
SELECT * FROM FROM Orders WHERE  Parent = 4 ORDER BY OrderID DESC Limit 1

此外,如果你有时间看看我的这个答案会给你一个很好的示范。

在 mysql 和 php 中寻找空闲时间块?

于 2012-09-18T10:20:15.893 回答
0
SELECT * FROM FROM Orders WHERE  OrderID = @orderId
UNION ALL 
SELECT * FROM FROM Orders WHERE  Parent = @orderId
于 2012-09-18T10:20:19.577 回答
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)

我不确定这个的性能虽然......

于 2012-09-18T10:20:25.453 回答
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
于 2012-09-18T10:31:49.183 回答
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
于 2012-09-18T11:27:02.667 回答