我有一个包含32行的表,成对行包含相同的“名称 - 值”,但具有不同的raspberry值(分别为“one”和“two”。)
我想用唯一名称和最低average_distance提取每一行 - 给我16行,为此我使用此查询:
SelectFinally();
function SelectFinally (){
$con = connectToDB();
$sql = "SELECT name,MIN(average_distance),raspberry From average GROUP BY name";
$result= mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
echo "number of rows" .$num_rows ."<br />";
while($row=mysqli_fetch_assoc($result)) {
extract($row);
$name = $row['name'];
$distance = $row['MIN(average_distance)']; //."<br />";
$raspberry = $row['raspberry']; //."<br />";
echo "select inside selectFinally name: " .$name ." distance: " .$distance ." raspberry " .$raspberry ."<br />";
}
}
这个查询给了我average_distance的最低值,但是它弄乱了我的覆盆子值。例如blå_bil的树莓值应为“2”,因此它的average_distance值最低。 我似乎无法做对。有人请帮助我做对吗?
答案 0 :(得分:1)
尝试:
SELECT a.name, a.raspberry
FROM average a
INNER JOIN
(
SELECT name, MIN(average_distance) as avg_dist
FROM average
GROUP BY name
) a2 ON a.name = a2.name AND a.average_distance = a2.avg_dist
而不是SELECT name,MIN(average_distance),raspberry From average GROUP BY name
答案 1 :(得分:0)
感谢Nishant Matha 它工作 - 我只需要在我的第一个选择中添加te raspberry。现在它将average_distance添加到输出中。
$sql = "SELECT a.name, a.average_distance, a.raspberry
from average a
INNER JOIN
(
select name,MIN(average_distance) AS avg_dist,raspberry
FROM average
GROUP BY name
)
a2 ON a.name=a2.name AND a.average_distance = a2.avg_dist ";