在 GROUP_CONCAT 语句中对值进行排序
在 MySQL 中,GROUP_CONCAT 根据特定分组组合来自一列的值。然而,连接值的顺序通常由分组发生的顺序确定。要控制这些值的排序,需要特定的语法。
要对 GROUP_CONCAT 语句中的串联值进行排序,请在嵌套查询中使用 ORDER BY 子句。例如,考虑以下查询:
GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.id = l.competence AND parent.id != 1 ORDER BY parent.lft) SEPARATOR "<br />\n") AS competences
要按升序对连接的能力值进行排序,请按如下方式修改查询:
GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.id = l.competence AND parent.id != 1 ORDER BY parent.lft ASC) SEPARATOR "<br />\n") AS competences
类似地,要按降序对值进行排序顺序,在 ASC 之后使用 DESC 关键字:
GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.id = l.competence AND parent.id != 1 ORDER BY parent.lft DESC) SEPARATOR "<br />\n") AS competences
以上是如何控制 MySQL GROUP_CONCAT 语句中值的顺序?的详细内容。更多信息请关注PHP中文网其他相关文章!