扩展到我的MySQL查询。需要比较不同行和列的值

时间:2012-12-11 16:05:47

标签: mysql

这是我的表:

enter image description here

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

enter image description here

这是查询:

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 spread2 与来自 row2 spread1 进行比较,并获取代码和更大的点差数量case spread2

为什么我要比较来自row1的 spread2 和来自row2的 spread1 是因为它们与自己重叠。所以,我正在比较重叠中的点差:

enter image description here

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

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

我尝试过添加:

ORDER BY (spread2,spread1) DESC LIMIT 1

并且我确信它不会像我想要的那样比较来自同一行的值。

1 个答案:

答案 0 :(得分: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

当我得到一行时它也有效。