MySQL:选择元组的最大值

时间:2013-11-30 05:48:38

标签: mysql join max greatest-n-per-group

我有一个小部件表和一个事件表,以及一个连接它们的联结表。联结表包含可能在事件期间更改的窗口小部件属性(如果为非null)。 修改:我创建了一个fiddle,其中包含一些示例数据和一个示例查询。

插件:

id        int
name      varchar(50)

事件:

id        int
time      datetime

widget_event

widget_id int
event_id  int
prop1     decimal(8,4) NULL
prop2     int          NULL
...
propN     typeN        NULL

我想为每个属性选择最近的非空值,大致有以下查询:

select
    widget.id,
    widget.name,
    max((event1.time, event1.id, widget_event1.prop1)),
    max((event2.time, event2.id, widget_event2.prop2)),
    ...
    max((eventN.time, eventN.id, widget_eventN.propN)),
from
    widget
    left join (widget_event widget_event1, event event1) 
        on widget_event1.widget_id = widget.id 
        and widget_event1.event_id = event1.id
        and widget_event1.prop1 is not null
    left join (widget_event widget_event2, event event2) 
        on widget_event2.widget_id = widget.id 
        and widget_event2.event_id = event2.id
        and widget_event2.prop2 is not null
    ...
group by
    widget.id

据我所知,在max表达式中使用元组是不合法的,我能想到的最好的是这个更复杂的查询(基于the answer to "Get records with highest/smallest per group"):

select
    widget.id,
    widget.name,
    widget_event1.prop1,
    widget_event2.prop2,
    ...
    widget_eventN.propN
from
    widget
    left join (widget_event widget_event1, event event1) 
        on widget_event1.widget_id = widget.id 
        and widget_event1.event_id = event1.id
        and widget_event1.prop1 is not null
    left join (widget_event widget_event1_f, event event1_f) 
        on widget_event1_f.widget_id = widget.id 
        and widget_event1_f.event_id = event1_f.id
        and widget_event1_f.prop1 is not null
        and (event1_f.time, event1_f.id) > (event1.time, event1.id)
    left join (widget_event widget_event2, event event2) 
        on widget_event2.widget_id = widget.id 
        and widget_event2.event_id = event2.id
        and widget_event2.prop2 is not null
    left join (widget_event widget_event2_f, event event2_f) 
        on widget_event2_f.widget_id = widget.id 
        and widget_event2_f.event_id = event2_f.id
        and widget_event2_f.prop2 is not null
        and (widget_event2_f.time, widget_event2_f.id) > (widget_event2.time, widget_event2.id)
    ...
where
    widget_event1_f.prop1 is null
    and widget_event2_f.prop2 is null
    ...
    and widget_eventN_f.propN is null
group by
    widget.id

是否有更简单的方法来编写此查询?您可以比较元组但不能选择元组的最大值似乎很奇怪,所以我希望有一点简单的语法这将减少容易出错的样板量。

0 个答案:

没有答案