2017-06-19 63 views
7

如何根據USER SCORE字段以最接近SCORE BRAND字段值的規定確定表用戶的RESULTS字段。如何在PHP中找到最接近的值

enter image description here

這是表品牌

<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> 

這是表的用戶

<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> 
+0

你嘗試過什麼到目前爲止? –

+0

如果用戶評分爲「55」,那麼結果如何? 'Axa'或'Autocilin'? –

+0

即時通訊只是嘗試與其他條件,但不工作。 55應該是autocilin。 –

回答

0
select * 
from table 
order by abs(value - $myvalue) 
limit 1 
+1

你能描述變量$ myvalue嗎? –

+0

$ myvalue是您正在查找的分數 - 這將導致每個品牌1個查詢 - Roman Hocke的答案做同樣的事情,但在1總體查詢 –

0

你應該有一些預先定義的閾值,以匹配周圍(讓1分與1000分不相符)。

SELECT .. WHERE score_brand >= score_user - :epsilon AND score_brand <= score_user + :epsilon 
+0

沒有預定義的閾值,它的診斷聲明基於品牌 –

0

最後我得到了一些漂亮的解決方案:

SELECT u.*, b.nama_lengkap as result 
FROM `users` AS u 
JOIN `brands` AS b 
WHERE (b.score - u.score) > 0 
AND (b.score - u.score) < 10 
ORDER BY u.id; 

b.nama_lengkap - >名牌

我剛剛加入兩個表,並做了一些算術運算來獲得相應的行。

編輯

SELECT v.id, v.username, v.score, b.nama_lengkap AS result 
FROM (SELECT users.id, users.score, users.username, min(brands.score) nextSc 
     FROM users 
     LEFT JOIN brands 
     ON users.score <= brands.score 
    GROUP BY users.id, users.score) AS v 
LEFT JOIN brands b 
    ON v.nextSc = b.score 
ORDER BY v.id, v.score; 

這是任何multiplicated值完整的動態查詢。它會讓你獲得用戶品牌的封閉分數。

你可以找到LIVE DEMO HERE

+0

等等...我試試看... –

+0

@SigitPrasetya,發生了什麼事?我的查詢不起作用? –

+0

它的工作...但只適用於10的倍數。如何倍數2,3,...,和大於10 –

3

您可以選擇使用子查詢找到合適的品牌像這樣每個用戶選擇:

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