[英]Combining records from two Mysql tables
I have two tables: 我有两个表:
records 记录
id subrecord_of
1 0
2 1
3 0
4 1
5 0
6 5
values 值
id value
1 11
1 111
2 222
2 222
2 2222
3 33
4 44
6 66
6 666
The goal is to select records not being subrecords 目标是选择不是子记录的记录
with corresponding sum of values from records and subrecords: 具有来自记录和子记录的值的相应总和:
id sub sum_of_values
1 2,4 11,111,2222,222,44
3 null 33
5 6 666,66
column "id" - records where sub is 0 列“ id”-记录sub为0
column "sub" - list of subrecords fe id 2 and id 4 are subrecords of id 1 列“ sub”-子记录fe id 2和id 4的列表是id 1的子记录
column "values" - list of unique values fe id 1 = distinct values from id1 + id2 + id4 “值”列-唯一值列表fe id 1 =与id1 + id2 + id4不同的值
Any help? 有什么帮助吗?
This is tricky, because the joins are going to generate a bunch of extra rows. 这很棘手,因为联接将生成一堆额外的行。 The key idea for brining the data together is
group_concat()
and group by
. 将数据连接在一起的关键思想是
group_concat()
和group by
。
The following will work: 以下将起作用:
select r.id,
group_concat(distinct rs.id) as sub,
group_concat(distinct v.value) as values
from records r left join
records rs
on rs.subrecordof = r.id left join
values v
on v.id in (r.id, rs.id)
where r.subrecordof = 0
group by r.id;
Performance will not be particularly good. 性能不会特别好。 So, this solution should work well on smallish data sets.
因此,此解决方案应在较小的数据集上很好地工作。 It might not work well on large data sets.
在大型数据集上可能无法很好地工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.