mysql按列值分组成行,MYSQL Group按列分组,每行2行

I need 2 id for each group.

SELECT `id`, `category`.`cat_name`

FROM `info`

LEFT JOIN `category` ON `info`.`cat_id` = `category`.`cat_id`

WHERE `category`.`cat_name` IS NOT NULL

GROUP BY `category`.`cat_name`

ORDER BY `category`.`cat_name` ASC

How to do this?

Sample Data:

id cat_name

1 Cat-1

2 Cat-1

3 Cat-2

4 Cat-1

5 Cat-2

6 Cat-1

7 Cat-2

Output Will be:

id cat_name

6 Cat-1

4 Cat-1

7 Cat-2

5 Cat-2

解决方案

If you need two arbitrary ids, then use min() and max():

SELECT c.`cat_name` , min(id), max(id)

FROM `info` i INNER JOIN

`category` c

ON i.`cat_id` = c.`cat_id`

WHERE c.`cat_name` IS NOT NULL

GROUP BY c`.`cat_name`

ORDER BY c.`cat_name` ASC ;

Note: You are using a LEFT JOIN and then aggregating by a column in the second table. This is usually not a good idea, because non-matches are all placed in a NULL group. Furthermore, your WHERE clause turns the LEFT JOIN to an INNER JOIN anyway, so I've fixed that. The WHERE clause may or may not be necessary, depending on whether or not cat_name is ever NULL.

If you want the two biggest or smallest -- and can bear to have them in the same column:

SELECT c.`cat_name`,

substring_index(group_concat id order by id), ',', 2) as ids_2

FROM `info` i INNER JOIN

`category` c

ON i.`cat_id` = c.`cat_id`

WHERE c.`cat_name` IS NOT NULL

GROUP BY c`.`cat_name`

ORDER BY c.`cat_name` ASC ;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值