How to find the nearest 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

<th>BRAND NAME</th>
<th>SCORE BRAND</th>
$sql = mysql_query("SELECT * FROM brand");
echo "<tr>

This is table users

<th>USER NAME</th>
<th>SCORE USER</th>
$sql2 = mysql_query("SELECT * FROM users");
echo "<tr>
<td> ??? </td>

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

SELECT u.*, (
    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