我在MySQL数据库中有一个表,其中包含一个级别列表(1-10)并且有一个XP_NEEDED列,我已经有一个数字,我想从该数字中找到该级别(该数字是XP) ,我知道如何以下面的方式做到这一点......
Example (Short):
if ($xpLookingFor >= 100 && $xpLookingFor < 200) // Checks if not high as level 2 {
return '1'; // Would be returning Level1
}
else if ($xpLookingFor >= 200 && $xpLookingFor < 300) // Checks if not high as level 3 {
return '2'; // Would be returning Level2
}
因此它检查它是否高于当前级别但不高于xp_needed之上的级别,如果它高达下一级if语句将处理它的下一级别。
但是这种方式有很多可能缩短的代码,最好的方法是什么?是否有内置的mysql功能?
答案 0 :(得分:2)
我不确定这是否是你需要的问题不太清楚。
<?php
function getLevel($xp, $maxLevel) {
for($check = 1; $check < $maxLevel; $check++)
if ($xp >= ($check*100) AND $xp < ($check*100)+100) return $check;
return $maxLevel;
}
//Param #1 is the xp level and #2 is the max level
echo getLevel(503, 10); // returns 5
echo getLevel(123, 10); //returns 1
echo getLevel(1405, 20); //returns 14
echo getLevel(1405, 10); //returns 10
?>
答案 1 :(得分:0)
因为您正在使用 DECLARE @SetA TABLE -- Create memory table for sample set A
(
ID INT NOT NULL
,D VARCHAR(5) NOT NULL
,V VARCHAR(5) NOT NULL
,A INT NOT NULL
)
DECLARE @SetB TABLE -- Create memory table for sample set B
(
ID INT NOT NULL
,D VARCHAR(5) NOT NULL
,V VARCHAR(5) NOT NULL
,A INT NOT NULL
)
INSERT INTO @SetA -- Create sample set A
(
ID
,D
,V
,A
)
SELECT 1, 'd1', 'v1', -70 UNION ALL
SELECT 2, 'd1', 'v2', 70 UNION ALL
SELECT 3, 'd1', 'v3', -70 UNION ALL
SELECT 4, 'd2', 'v1', 120
INSERT INTO @SetB -- Create sample set B
(
ID
,D
,V
,A
)
SELECT 1, 'd1', 'v11', -70 UNION ALL
SELECT 2, 'd1', 'v12', 70 UNION ALL
SELECT 3, 'd1', 'v13', -70 UNION ALL
SELECT 4, 'd2', 'v31', -120
;
WITH CTE_Total -- Join the two data sets and calculate the sum between all combinations.
AS
(
SELECT A.D
,A.V AS V_A
,B.V AS V_B
,(A.A + B.A) AS Total
,(CAST(A.A AS VARCHAR(10)) + ' ' + (CAST(B.A AS VARCHAR(10))) ) AS [Expression]
FROM @SetA A
INNER JOIN @SetB B ON A.D = B.D
)
,
CTE_ExpressionCounts -- Use ROW_NUMBER to determine number of occurrence of each A and B set combination for a specific expression.
AS
(
SELECT TOP 100 PERCENT
D
,V_A
,V_B
,[Expression]
,ROW_NUMBER() OVER (PARTITION BY [Expression] ORDER BY V_B) AS RepeatCount
FROM CTE_Total
WHERE Total = 0
ORDER BY V_B, V_A
)
SELECT D
,V
,SortOrder
FROM (
SELECT D
,V_A AS V
,((ROW_NUMBER() OVER (ORDER BY D, V_B) * 2) - 1) AS SortOrder
FROM CTE_ExpressionCounts
WHERE RepeatCount = 1
) A -- Select set A
UNION
SELECT D
,V
,SortOrder
FROM (
SELECT D
,V_B AS V
,((ROW_NUMBER() OVER (ORDER BY D, V_B) * 2) ) AS SortOrder
FROM CTE_ExpressionCounts
WHERE RepeatCount = 1
) B -- Select set B
ORDER BY SortOrder -- Note that the SortOrder column is not needed simply used to order result set.
,所以if的第一部分不需要,您可以将它们堆叠起来。
elseif