php - MYSQL 检索每组中的最后一条记录并按位置排序

标签 php mysql

这是我的 table

ID   Name   Qty   Location
1    B      1     Office
2    A      20    Office
3    A      50    Home
4    A      5     Office

这是我当前使用的sql语句:

select t1.* from itemtable t1 
    left join itemtable t2 on (t1.name = t2.name and t1.id < t2.id) 
    where t2.id is null AND t1.location = 'office' 
    order by name ASC

这在 phpadmin 中运行良好,但是当我在我的页面上运行它时,它首先对“id”进行排序。这意味着我会得到 B (因为 id = 1)然后是 A

如果有帮助,这是我的代码

<table class="table table-hover">
    <thead>
        <tr>
        <th style="text-align:left">ID.</th>
            <th style="text-align:left">Item</th>
        <th style="text-align:center">Quantity</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        $b = 0;
        $x = 1;
        while($row = $result->fetch_assoc()) {
            echo "<tr><td style=\"text-align:left\">". $x. "</td><td style=\"text-align:left\">". $row[name]. "</td><td style=\"text-align:center\">". $row[qty]. "</td></tr>";
        $b = $b + 1;
        $x = $x + 1;
        }?>
    </tbody>
</table>

最终输出为

ID   Name   Qty
1    B      1
2    A      75

如何让它按名称排序?谢谢

最佳答案

尝试下面的一个

Select t1.* FROM  (SELECT * FROM itemtable ORDER BY ID DESC ) as t1 group by Location

关于php - MYSQL 检索每组中的最后一条记录并按位置排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40276957/

相关文章:

php - PHP 的错误日志在 XAMPP 中的什么位置?

mysql - 需要刷新表吗?

c# - MySQL56 - 加载数据本地 INFILE - {"Parameter ' @url_hash' 必须定义。"} c#

php - MySQL 精确 URL 搜索

php - 具有多对一关系的单表继承 (STI)

php - SQL 从多个表中选择 *

php - 不能添加两个时间变量

php - pngquant PHP 示例不工作

php - MySQL + PHP + 根据多个输入查询表中的多列,不需要所有输入

PHP 更新 MySQL 列为空