How to find the nearest value in PHP

advertisements

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>


You can use subquery in selection to find proper brand for every selected user like this:

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