我正在更新现有数据库以简化它并扩展其功能。我有一张表如下:
ID Parent increment info 1 info 2
1 103 0 25 1
2 103 1 4 2
3 103 2 45 5
4 103 3 13 7
5 115 0 17 5
6 115 1 23 3
7 116 0 22 2
8 116 1 1 1
9 116 2 7 3
10 117 0 19 4
我希望新表只包含每个“父”的一条记录,并且该记录应该包含大多数字段,记录中的数据具有最大“增量”编号的父编号,但是对于信息2它应该记录最小'增量'的记录数据。
所需的输出如下:
ID Parent increment info 1 info 2
4 103 3 13 1
6 115 1 23 5
9 116 2 7 2
10 117 0 19 4
这种选择是否可以在Mysql中合并记录?
我已经看过使用Group by Parent,但是有相当数量的字段可以使用,所以我不确定它是否会起作用。我还查看了表的LEFT OUTER JOIN,以突出显示每个父级中具有最大增量的记录,但这不允许我选择具有相同父级但最小增量的记录数据。
难倒,非常感谢别人的帮助。
答案 0 :(得分:2)
是的,你可以这样做。假设您在附加字段中只有1到9的值:
select t.*
from t join
(select left(parent, locate(' ', parent) - 1) as p,
MAX(parent) as maxparent,
max(len
from t
group by left(parent, locate(' ', parent))
) tp
on left(t.parent, locate(' ', t.parent) - 1) = tp.p
where t.parent = tp.maxparent
如果数字超过9,则需要一些额外的摆弄,例如:
select *
from t join
(select left(parent, locate(' ', parent) - 1) as p,
max(SUBSTRING(parent, locate(' ', parent) + 1)) as maxval
from t
group by left(parent, locate(' ', parent))
) tp
on left(t.parent, locate(' ', t.parent) - 1) = tp.p
where t.parent = concate(tp.p, ' ', maxval)
修改后的数据结构:
select t.*
from t join
(select parent, MAX(increment) as maxi
from t
group by parent
) tp
on t.parent = tp.parent and t.increment = tp.maxi
答案 1 :(得分:1)
SELECT tt1.ID, tt1.Parent, MaxInc, tt1.info1, tt2.info2 FROM
(SELECT ID, Parent, MaxInc, info1 FROM test INNER JOIN
(SELECT Parent AS p, MAX(incr) AS MaxInc FROM test GROUP BY Parent) AS t1
ON Parent = p AND incr = MaxInc) AS tt1 INNER JOIN
(SELECT Parent, info2 FROM test INNER JOIN
(SELECT Parent AS p, MIN(incr) AS MinInc FROM test GROUP BY Parent) AS t2
ON Parent = p AND incr = MinInc) AS tt2 ON tt1.Parent = tt2.Parent
我将增量更改为incr