1、知识点
group_concat()函数:聚合函数
1、功能:将group by产生的同一个分组中的值连接起来,返回一个字符串结果。
2、语法:group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator ‘分隔符’] )
说明:通过使用distinct可以排除重复值;如果希望对结果中的值进行排序,可以使用order by子句;separator是一个字符串值,缺省为一个逗号。
示例:
GROUP_CONCAT(id ORDER BY score DESC,id ASC):
按照name分组后,获取每一组的id,按照 score DESC(score 降序拼接id),默认是通过逗号连接,如果id相同,id按照升序排序拼接,
substring_index()函数:
substring_index(str,delim,count)
str:要处理的字符串
delim:分隔符
count:计数
例子:str=www.wikibt.com
substring_index(str,‘.’,1)
结果是:www
substring_index(str,‘.’,2)
结果是:www.wikibt
如果count是正数,那么就是从左往右数,第N个分隔符的左边的所有内容
如果count是负数,那么就是从右往左数,第N个分隔符的右边的所有内容
substring_index(str,‘.’,-2)
结果为:wikibt.com
如果我要中间的的wikibt怎么办?
很简单的,两个方向:
从右数第二个分隔符的右边全部,再从左数的第一个分隔符的左边:
substring_index(substring_index(str,‘.’,-2),‘.’,1);
2、实践
1) 设置值为正
-- 190,229,304
-- 175,206,272,281,331,334
-- 当取值为3时
SELECT * FROM stock_storage_detail WHERE id IN(
SELECT substring_index(GROUP_CONCAT(id ORDER BY id desc),',',3) id
FROM stock_storage_detail
where source_type = 1 and factory_id = 9 and product_id in(72,203)
GROUP BY product_id)
1、分组拼接ID结果是两条:334,331,281 304,229,190 得到的拼接ID是ID所排的倒序的拼接
2、数据仍能查到334和304的数据,即所希望的分组分别第一条数据。这个无论设置的值是3还是几只要大于1即可
2) 设置值为负
1、当设置值为-1时
-- 190,229,304
-- 175,206,272,281,331,334
-- 当取值为-1时
SELECT * FROM stock_storage_detail WHERE id IN(
SELECT substring_index(GROUP_CONCAT(id ORDER BY id desc),',',-1) id
FROM stock_storage_detail
where source_type = 1 and factory_id = 9 and product_id in(72,203)
GROUP BY product_id)
得到190,175的数据
2、当设置值为-2时
-- 190,229,304
-- 175,206,272,281,331,334
-- 当取值为-1时
SELECT * FROM stock_storage_detail WHERE id IN(
SELECT substring_index(GROUP_CONCAT(id ORDER BY id desc),',',-3) id
FROM stock_storage_detail
where source_type = 1 and factory_id = 9 and product_id in(72,203)
GROUP BY product_id)
得到229,206的数据