0

这是我的桌子:

在此处输入图像描述

我想从中选择代码和编号,这是我的查询的可视化:

在此处输入图像描述

这是查询:

SELECT Code,Number,(1894 - Limit1) AS spread1,(Limit2 - 1894) AS spread2 
FROM MyTable WHERE Name="John" AND 600>=L1 AND 600<=L2 
AND 1894>=Limit1 AND 1894<=Limit2

如图所示,此查询返回两个值,我只需要一个。所以我应该比较row1中的spread2row2中的spread1并获取更大点差的代码和数量,在这种情况下它是.spread2

为什么我比较row1中的spread2和 row2 中的spread1是因为它们相互重叠。所以,我正在比较重叠范围内的价差:

在此处输入图像描述

通过上面的查询,我只能得到一两行,永远不会更多。为什么?因为表是这样创建的。如果结果出现一行,我将不需要任何比较,这意味着我只有一个代码和数字。

所以,归根结底,我需要扩展我的查询来做上面提到的事情。

我尝试的是添加:

ORDER BY (spread2,spread1) DESC LIMIT 1

而且我确信它不会比较值,因为我想要的是来自同一行的值。

4

1 回答 1

0

解决了!

对于 Value1 = 600 和 Value2 = 1894:

SELECT number,code,(spread2)AS spread FROM(SELECT number,code,@curRow := @curRow + 1 AS RowNumber, (1894 - Limit1) AS spread1,(Limit2 - 1894) AS spread2
FROM MyTable JOIN (SELECT @curRow := 0) r WHERE name="John" AND 600>=L1 AND 600<=L2 AND 1894>=Limit1 AND 1894<=Limit2)temp WHERE RowNumber=1
UNION
SELECT number,code,(spread1)AS spread FROM(SELECT number,code,@curRow := @curRow + 1 AS RowNumber, (1894 - Limit1) AS spread1,(Limit2 - 1894) AS spread2
FROM MyTable JOIN (SELECT @curRow := 0) r WHERE name="John" AND 600>=L1 AND 600<=L2 AND 1894>=Limit1 AND 1894<=Limit2)temp WHERE RowNumber=2
ORDER BY spread DESC limit 1

当 Value1 = 950 且 Value2 = 2400 时:

SELECT number,code,(spread2)AS spread FROM(SELECT number,code,@curRow := @curRow + 1 AS RowNumber,(2400 - Limit1) AS spread1,(Limit2 - 2400) AS spread2
FROM MyTable JOIN (SELECT @curRow := 0) r WHERE name="John" AND 950>=L1 AND 950<=L2 AND 2400>=Limit1 AND 2400<=Limit2)temp WHERE RowNumber=1
UNION
SELECT number,code,(spread1)AS spread FROM(SELECT number,code,@curRow := @curRow + 1 AS RowNumber,(2400 - Limit1) AS spread1,(Limit2 - 2400) AS spread2
FROM MyTable JOIN (SELECT @curRow := 0) r WHERE name="John" AND 950>=L1 AND 950<=L2 AND 2400>=Limit1 AND 2400<=Limit2)temp WHERE RowNumber=2
ORDER BY spread DESC limit 1

结果当我得到一排时它也有效。

于 2012-12-13T09:01:25.823 回答