mysql group_concat 用法

栏目: 数据库 · Mysql · 发布时间: 9年前

内容简介:mysql中group_concat用法。group_concat(),手册上说明:该函数返回带有来自一个组的连接的非NULL值的字符串结果。通俗点理解,其实是这样的:group_concat()会计算哪些行属于同一组,将属于同一组的列显示出来。要返回哪些列,由函数参数(就是字段名)决定。分组必须有个标准,就是根据group by指定的列进行分组。

需求:从一批数据中,按 live_id 分组取 id 最大的一个值,并按照 sort desc create_time 排序

测试数据如下:

mysql group_concat 用法

可以看到有些 live_id 对应多条数据记录

解决方法:

<?php
$sql = "select
        SUBSTRING_INDEX(group_concat(lpad(sort, 5, 0) order by id desc),',', 1) as sort,
        SUBSTRING_INDEX(group_concat(id order by id desc),',', 1) as id,
        SUBSTRING_INDEX(group_concat(create_time order by id desc),',', 1) as create_time
        from live_view where is_show=1 and status=0 group by live_id order by sort desc,create_time desc  limit {$limit},{$pagesize}";
$ret = $this->fetchAllRows($sql);
if(!$ret)
{
    return array();
}

$ids = array();
foreach ($ret as $value)
{
    $ids[] = $value['id'];
}
$ids_str = implode(',', $ids);

$sql = "select {$viewfields} from live_view
        where id in({$ids_str}) order by sort DESC,create_time DESC ";
$ret = $this->fetchAllRows($sql);

从代码中看到,我们先通过 mysql group_concat SUBSTRING_INDEX 两个函数获获取到想要的数据 ID,再根据这些 ID 来获取其余字段信息


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Distributed Algorithms

Distributed Algorithms

Wan Fokkink / The MIT Press / 2013-12-6 / USD 40.00

This book offers students and researchers a guide to distributed algorithms that emphasizes examples and exercises rather than the intricacies of mathematical models. It avoids mathematical argumentat......一起来看看 《Distributed Algorithms》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

SHA 加密
SHA 加密

SHA 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具