2016-02-13 19 views
1

我需要在兩列中獲得兩個數字的記錄。但是我需要找到最小值是其中一列的位置。並找到與該最小號碼對齊的號碼。選擇一個記錄,其中最前面的列中的數據最少

現在,我有以下幾點:

$sql = "SELECT ID, MIN(price) AS minPrice FROM my_table"; 
$result = $conn->query($sql); 
$row = $result->fetch_assoc(); 

echo $row["minPrice"]; // This works 
echo $row["ID"]; // This is not the number that is in the record where minPrice is. 

回答

0

您需要使用子查詢。

Select ID from my_table t, (select min(price) as minPrice from my_table) where t.price =minPrice; 

沒有測試它,但它應該工作。

它以最低的價格返回所有ID。

1

如果您正在尋找一排,最簡單的方法是order bylimit

select t.* 
from t 
order by t.col2 asc 
limit 1; 
相關問題