How to find the closest value in PHP
How to determine the RESULTS field in table users, base on USER SCORE field with the provisions of the value closest to SCORE BRAND field.
This is table Brand
<table>
<tr>
<th>BRAND NAME</th>
<th>SCORE BRAND</th>
</tr>";
$sql = mysql_query("SELECT * FROM brand");
while($m=mysql_fetch_array($sql)){
echo "<tr>
<td>$m[brand_name]</td>
<td>$m[score]</td><tr>";
}
</table>
This is table users
<table>
<tr>
<th>USER NAME</th>
<th>SCORE USER</th>
<th>RESULT</th>
</tr>";
$sql2 = mysql_query("SELECT * FROM users");
while($u=mysql_fetch_array($sql2)){
echo "<tr>
<td>$u[username]</td>
<td>$u[score]</td>
<td> ??? </td>
<tr>";
}
</table>
您可以在选择中使用子查询为每个选定的用户找到适当的品牌,例如:
SELECT u.*, (
SELECT b.id
FROM brand AS b
ORDER BY ABS(b.score - u.score) ASC, b.score DESC -- selects brands ordered by their difference from user's score
LIMIT 1 -- get just the first brand (with score closest to user's)
)
FROM user AS u
select *
from table
order by abs(value - $myvalue)
limit 1
你应该有一些预先定义的阈值来匹配周围(因此得分1与得分1000不匹配)。
SELECT .. WHERE score_brand >= score_user - :epsilon AND score_brand <= score_user + :epsilon
链接地址: http://www.djcxy.com/p/39834.html
下一篇: 如何在PHP中找到最接近的值