mysql concat 限制,MySQL group_concat限制分组中的行

The next example is my database.

tb_port

id port

1 80

2 22

3 53

4 3128

5 443

tb_dest

id dest

1 network

2 local

tb_rule

id id_port id_dest

1 1 1

2 2 1

3 3 1

4 4 1

5 5 1

Select:

select dest,group_concat(port) from tb_port a, tb_dest b, tb_rule c where a.id=c.id_port and b.id=c.id_dest group by dest

Result:

network 80,22,53,3128,443

but is not the result I'm looking for, the result would be this.

Select ex:

select dest,group_concat(port limit 2) from tb_port a, tb_dest b, tb_rule c where a.id=c.id_port and b.id=c.id_dest group by dest

result I would like

network 80,22

network 53,3128

network 443

how to achieve this result only with SQL?

解决方案

MySQL doesn't make this kind of query easy, but one (admittedly not very pretty) solution is to use a variable to give each row a sequence number per dest and just group by the row number integer divided by 2 to get two numbers in each group;

SELECT dest, GROUP_CONCAT(port ORDER BY rank) ports

FROM (

SELECT dest, port, (

CASE dest WHEN @curDest

THEN @curRow := @curRow + 1

ELSE @curRow := 1 AND @curDest := dest END) rank

FROM tb_port a

JOIN tb_rule c ON a.id = c.id_port

JOIN tb_dest b ON b.id = c.id_dest,

(SELECT @curRow := 0, @curDest := '') r

ORDER BY dest

) z

GROUP BY FLOOR(rank/2),dest

ORDER BY dest, MIN(rank)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值