mysql怎么合并行,如何在MySQL中合并多行?

I ran into some problems while structuring my database, and I will ask two questions.

First question: below table needs to be merged by the same IDs

╔═════╦═══════╦═════╦═══════╗

║ id* ║ name ║ age ║ grade ║

╠═════╬═══════╬═════╬═══════╣

║ 0 ║ John ║ ║ ║

║ 0 ║ ║ 11 ║ ║

║ 0 ║ ║ ║ 6 ║

║ 1 ║ Dave ║ ║ ║

║ 1 ║ ║ 12 ║ ║

║ 1 ║ ║ ║ 7 ║

╚═════╩═══════╩═════╩═══════╝

so it should look like this;

╔═════╦═══════╦═════╦═══════╗

║ id* ║ name ║ age ║ grade ║

╠═════╬═══════╬═════╬═══════╣

║ 0 ║ John ║ 11 ║ 6 ║

║ 0 ║ Dave ║ 12 ║ 7 ║

╚═════╩═══════╩═════╩═══════╝

NOTE: id* is not AUTO_INCREMENT

Second question: You probably think that the former database structure is poor. The good thing is, I haven't created the database yet and I have been looking for a solution to add data to an existing row without removing old information, but if there is no old information, it would create a new row. Thanks in advance.

Second question explained

Virgin table

╔═════╦═══════╦═════╦═══════╗

║ id* ║ name ║ age ║ grade ║

╠═════╬═══════╬═════╬═══════╣

║ ║ ║ ║ ║

╚═════╩═══════╩═════╩═══════╝

some SQL statement

╔═════╦═══════╦═════╦═══════╗

║ id* ║ name ║ age ║ grade ║

╠═════╬═══════╬═════╬═══════╣

║ 0 ║ John ║ ║ ║

╚═════╩═══════╩═════╩═══════╝

the same SQL statement with different parameters

╔═════╦═══════╦═════╦═══════╗

║ id* ║ name ║ age ║ grade ║

╠═════╬═══════╬═════╬═══════╣

║ 0 ║ John ║ ║ ║

║ 1 ║ Dave ║ ║ ║

╚═════╩═══════╩═════╩═══════╝

another SQL statement

╔═════╦═══════╦═════╦═══════╗

║ id* ║ name ║ age ║ grade ║

╠═════╬═══════╬═════╬═══════╣

║ 0 ║ John ║ ║ ║

║ 1 ║ Dave ║ 12 ║ ║

╚═════╩═══════╩═════╩═══════╝

another SQL statement

╔═════╦═══════╦═════╦═══════╗

║ id* ║ name ║ age ║ grade ║

╠═════╬═══════╬═════╬═══════╣

║ 0 ║ John ║ ║ 6 ║

║ 1 ║ Dave ║ 12 ║ ║

╚═════╩═══════╩═════╩═══════╝

... and so on.

解决方案

You should be able to apply an aggregate function to all the columns and then GROUP BY id:

select id,

max(name) name,

max(age) age,

max(grade) grade

from yourtable

group by id

As far as the DB structure, the only issue that I see is that you are inserting multiple records for the same user. You should be using an UPDATE statement to use the values instead of inserting.

It sounds like you want to use the REPLACE function in MySQL (here is a tutorial).

So the query would be similar to this:

REPLACE

INTO yourtable (`id`, `name`, `age`, `grade`)

VALUES (0, 'john', 11, null);

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值