我有一个MySQL表,如下所示:
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| Weight | int | YES | | NULL | |
| 100 | double | YES | | NULL | |
| 120 | double | YES | | NULL | |
| 130 | double | YES | | NULL | |
| 150 | double | YES | | NULL | |
| 160 | double | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
我使用
选择一行$row = mysqli_query($con, "SELECT * FROM Rates WHERE Weight<='$weight' AND Weight>='$weight'");
我的问题是使用返回的查询结果如何打印其中一个最接近用户输入的字段(100,120,130,150,160)的值。
例如,用户键入110,将打印字段“120”中的值。 或者,如果输入131,则将打印“150”的值(因此总是向上舍入)。
现在我有:
while($row = mysqli_fetch_array($rate))
{
echo "Using weight your cost is: " . $row['100'];
echo "<br>";
}
但这只打印字段'100'的值 如何替换它以获取用户输入并确定哪些行最接近并打印
类似于:
IF ($value =< 100) echo $row['100']
IF ($value =< 120 && $value > 100) echo $row['120']
IF ($value =< 130 && $value > 120) echo $row['130']
..etc
答案 0 :(得分:1)
尝试此版本的查询:
SELECT *
FROM Rates
order by abs(Weight - $weight)
limit 1;
返回一行,其中权重最接近用户值。
以下版本总是四舍五入:
SELECT *
FROM Rates
WHERE Weight >= $weight
order by Weight
limit 1;
编辑:
根据您的编辑,我认为这可能是您正在寻找的内容:
SELECT (case when "100" >= $value then "100"
when "120" >= $value then "120"
when "130" >= $value then "130"
when "150" >= $value then "150"
when "160" >= $value then "160"
end)
FROM Rates
WHERE Weight<='$weight' AND Weight>='$weight';
case
选择第一个匹配值。
答案 1 :(得分:0)
您可以尝试此版本。
SELECT *
FROM Rates
WHERE Weight>='$weight'"
limit 1;
它只返回一行。你可以获取值
$row = mysqli_fetch_array($rate);
echo "Using weight your cost is: " . $row['Field'];
echo "<br/>";
答案 2 :(得分:0)
听起来你需要一个if/else
块来设置你的字段 -
if($your_value <= 100) {$field = 100;}
else if($your_value <= 120) {$field = 120;}
else if($your_value <= 130) {$field = 130;}
else if($your_value <= 150) {$field = 150;}
else {$field = 160;}
while($row = mysqli_fetch_array($rate))
{
echo "Using weight your cost is: " . $row[$field];
echo "<br>";
}