首页 > 解决方案 > 如何分组 GROUP_CONCAT()?

问题描述

例如,我正在寻找一种在单个查询中获取 GROUP_CONCAT() 函数组的方法。

我当前的代码

SELECT
    SUBSTRING_INDEX(GROUP_CONCAT(service_info.ip_address SEPARATOR ','),',',service_plans.aggregation) AS ip_address
FROM
    services
LEFT JOIN
    service_info
ON
    service_info.service_id = services.id
LEFT JOIN
    service_plans
ON
    service_plans.id = services.service_plan_id
WHERE
    service_plans.id = '2'

我想按特定数字(如果您在查询中看到 $group_by 变量)对 IP 地址进行分组,然后用不同的字符(例如“:”或其他字符)分隔。

本质上,我希望我的输出看起来像:

如果 $group_by=2: 10.1.1.2,10.1.1.3:10.1.1.4,10.1.1.5

如果 $group_by=3: 10.1.1.2,10.1.1.3,10.1.1.4:10.1.1.5

这可以实现到我当前的查询中吗?

更新:表结构

桌子service_plans id | name | aggregation ----------------------------------------- 1 | Uncapped 10Mbps 20:1 | 20 2 | Uncapped 20Mbps 10:1 | 10 3 | Capped 30Mbps | 0

桌子services id | service_plan_id | description ------------------------------------ 1 | 2 | Phone 2 | 2 | Laptop 3 | 2 | PC 4 | 2 | TV 5 | 2 | Test

桌子service_info id | service_id | ip_address ------------------------------ 1 | 1 | 10.1.1.2 2 | 2 | 10.1.1.3 3 | 3 | 10.1.1.4 4 | 4 | 10.1.1.5 5 | 5 | 10.1.1.6

我正在尝试获取由逗号连接和分隔的 ip_address 数组,但无论值是多少,组中的service_plans.aggregation值都是。

如果聚合为 2,那么我的输出应该是: 10.1.1.2,10.1.1.3:10.1.1.4,10.1.1.5 如您所见,它们以 2 为一组,然后下一组用冒号分隔(:)

如果聚合是 3,那么我的输出应该是: 10.1.1.2,10.1.1.3,10.1.1.4:10.1.1.5 正如您所看到的,它们以 3 为一组,然后下一组由冒号(:)分隔,并且很快

标签: phpmysql

解决方案


你的帖子有点混乱。如果您发布示例数据,然后发布您希望查询返回的内容,将会有所帮助。我会根据您的帖子主题回答我认为您要问的问题。

ServicePlanIP

service_plan_id | ip_address
-------------------------------
 1              | 192.168.70.1
 1              | 192.168.70.2
 1              | 192.168.70.3
 2              | 192.168.70.4
 2              | 192.168.70.5
 2              | 192.168.70.6

如果您针对 ServicePlanIP 运行此查询:

SELECT service_plan_id, GROUP_CONCAT(ip_address) as ip_addresses
FROM ServicePlanIPs
GROUP BY service_plan_id

你会得到:

service_plan_id | ip_addresses
-------------------------------
 1              | 192.168.70.1, 192.168.70.2, 192.168.70.3
 2              | 192.168.70.4, 192.168.70.5, 192.168.70.6

推荐阅读