mysql如何将多行数据合并成一行

mysql如何将多行数据合并成一行,第1张

您好.

以前有高人写过类似的:

select id,group_concat(re_id order by re_id separator ",") as re_id

from tablename

group by id

方法2:

select group_concat(list_name) from aa_list

如果还有问题,可以继续追问,感谢。

1、先添加完,删除所有重复的记录,再insert一次

insert into A select * from B

insert into A select * from C

insert into A select * from D

2、删除重复的记录只保留一行

delete from A where name in (select id from t1 group by id having count(id) >1)and rowid not in (select min(rowid) from t1 group by id having

count(*)>1)

3、记录一下这些重复的记录,

mysql -uroot -p123456 -Ddb01 -e 'select b.id from t1 b group by id having count(b.id) >1' | tail -n +2 >repeat.txt

删除全部重复的记录

delete from A where name in (select name from t1 group by name having count(name) >1)

再次插入多删的重复记录

#!/bin/sh

for id1 in `cat repeat.txt`do

mysql -uroot -p123456 -Ddb01 -e "insert into A select * from B where id='${id1}'"

done

BEGIN

declare sel_sql VARCHAR(100)

declare g_sql VARCHAR(100)

declare u_sql VARCHAR(100)

declare t_name VARCHAR(100)

DECLARE done INT DEFAULT FALSE

declare month_cursor CURSOR for select month from fee_month where flag=1

declare CONTINUE HANDLER for not found set done=true

set sel_sql='(select sum(fee + fee2 + fee3) As fee,month from fee_detail_'/*左括弧*/

set g_sql=' group by month ) '/*右括弧*/

set u_sql=' union all '/*加空格、上同*/

OPEN month_cursor

my_loop:loop

FETCH month_cursor into t_name

if done then 

leave my_loop

end if

if s_sql is null then

set @s_sql= CONCAT(sel_sql,t_name,g_sql)/*第一个SQL*/

else

set @s_sql= CONCAT(s_sql, u_sql, sel_sql, t_name, g_sql)/*开始Union后续SQL*/

end if

end loop

/*最后执行一次拼接后的SQL语句*/

PREPARE pre_s_sql from @s_sql

EXECUTE pre_s_sql

deallocate prepare pre_s_sql

close month_cursor

END

思路修正,貌似还有不少语法问题,自行修复。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/8367835.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-15
下一篇2023-04-15

发表评论

登录后才能评论

评论列表(0条)

    保存