【发布时间】:2015-06-30 05:53:15
【问题描述】:
我正在寻找一种(更清洁的?)方法来执行以下操作:
假设我有一个主表,有大约 15 列,看起来像这样,每个 id 一行:
主要的: id 开始结束 col4 ... col15 666 2014-01-01 2014-06-30 ... ... ... 1234 2015-03-05 2015-05-02 ... ... ... 9876 2014-09-01 2015-01-01 ... ... ... ...(ETC)然后我有另一个表,事件,每个 id 可能有 0、1 或许多行:
事件: 身份证日期代码 666 2014-01-20 “code_a” 1234 2015-05-01 “code_b” 666 2014-01-25 “code_c” 666 2014-02-09 “code_z” ... (ETC)最后我有一个表格,代码,每个代码有一行,给出代码的描述以及类型(0,1 或 2):
代码: 代码描述类型 “code_a” “某事” 0 “code_b”“其他”1 “code_c”“另一件事”0 “code_d” “还有一个” 2 (无代码 z)我想要的结果是 main 的 15 列加上三个附加列,其中包含按类型在该 id 的开始日期和结束日期之间发生的事件代码的逗号分隔列表(第一列是类型 0,第二列是 1,第三种类型 2),所以:
id start end ... col15 type_0 type_1 type_2 666 2014-01-01 2014-06-30 ... ... "code_a,code_c" 1234 2015-03-05 2015-05-02 ... ... "code_b" ...(ETC)我的解决方案是
select m.*
, group_concat(c0.code) as type_0
, group_concat(c1.code) as type_1
, group_concat(c2.code) as type_2
from main m
left join events e on m.id = e.id and e.date between m.start and m.end
left join codes c0 on c0.code = e.code and c0.type = 0
left join codes c1 on c1.code = e.code and c1.type = 1
left join codes c2 on c2.code = e.code and c2.type = 2
group by m.id
, m.start
, m.end
, m.col4
, m.col5
, m.col6
, m.col7
, m.col8
, m.col9
, m.col10
, m.col11
, m.col12
, m.col13
, m.col14
, m.col15
但对我来说,这看起来很讨厌。有没有更优雅的方法来做到这一点(尤其是避免分组依据中列出的 15 列)?
【问题讨论】:
-
射击。我确定这很清楚,但 c1 和 c2 的连接应该分别表示 c1.code、c1.type 和 c2.code、c2.type。
-
您知道您可以编辑自己的问题吗?
-
您的查询是否运行?我怀疑你的
group_concat -
没有看到编辑按钮。修复了 group_concats 中的列和连接中的表名。 @Rahul 这是真正问题的简化版本,涉及更长的表名和列名......