Php / MYSQl输出查询foreach值的第一个和最后一个结果的值?

时间:2016-09-05 15:07:25

标签: php mysql arrays

我正在寻找关于如何为数组的每个值输出查询的第一个和最后一个值的php示例。我可能看起来很明显......但这就是我所拥有的。

$userId = $_SESSION['userId'];
$sourceID = $_POST['sourceID'];
ProcessDate= $_POST['processDate'];

$result = $conn->query("SELECT location_id FROM inventory
where source_date = '$sourceID' and source_id = '$sourceID' and created_by= '$userId'");
while($row = $result->fetch_assoc()) {
            $location_id[$x] = $row['location_id'];

    $x++;
}

我想获取$ location_id的每个值并运行查询

$resultF = $conn->query("Select sku from inventory where  location_id="$location_id" Order by sku ASC ");
while($row = $resultF->fetch_assoc()) {
$firstsku= $row['sku']; }           
$resultL = $conn->query("Select sku from inventory where location_id="$id" Order by sku DSC ");
while($row = $resultL->fetch_assoc()) {
    $lastsku= $row['sku'];}

每个location_id的输出为$ firstsku,$ lastsku,location_id

1 个答案:

答案 0 :(得分:2)

因为您使用的是ORDER BY sku,所以我推断它确实拥有良好的“可排序”值,因此可以在一个简化的查询中利用GROUP BY结合MAX来完成和MIN函数:

SELECT location_id, MAX(sku) AS lastsku, MIN(sku) AS firstsku 
    FROM inventory
    WHERE source_date = '$sourceID'
        AND source_id = '$sourceID'
        AND created_by= '$userId' 
    GROUP BY location_id