不使用UNION重写MySQL查询

时间:2014-04-22 12:38:00

标签: mysql sql join union greatest-n-per-group

我有以下查询返回正确的结果,但我确定这不是获得这些结果的最佳方式...

select * from (
    select * from features where feature_area = 0 
    order by updateStamp desc limit 1
) as feature_1

union all

select * from (
    select * from features where feature_area = 1 
    order by updateStamp desc limit 1
) as feature_2

union all

select * from (
    select * from features where feature_area = 2 
    order by updateStamp desc limit 1
) as feature_3

这会返回看起来像......

的结果
id    feature_area        title                  updateStamp
--------------------------------------------------------------------
103   0                   This is a title        2014-04-15 09:26:14
102   1                   Another title          2014-03-27 14:09:49
98    2                   More title             2014-01-21 16:00:55

使用连接而不是工会可以改善这种情况吗?如果可以的话,请指出我正确的方向。

修改

看了@Ben指出的其他选项后,我似乎已经得到了最快的查询(虽然没有那么吸引人),这是出于我的特殊目的。如果您认为我错了,请随意纠正我。我不是专家,因此我在征求意见。

4 个答案:

答案 0 :(得分:0)

select f.* from features f
inner join (
    select
    feature_area
    max(updateStamp) as updateStamp
    from
    features 
    where feature_are IN (0,1,2)
    group by feature_area
) sq  on sq.feature_area = f.feature_area 
and sq.updateStamp = f.updateStamp

答案 1 :(得分:0)

希望我能正确阅读你的问题。

select *
From features f
inner join ( select feature_area, max(updateStamp) as maxUpdateStamp
             from features
             Group by feature_area
            ) as minfeatures
           ON minfeatures.feature_area = f.feature_area
           AND minfeatures.maxUpdateStamp = f.updateStamp

答案 2 :(得分:0)

with MaxFeature
AS
(
select 
    feature_area        AS  feature_area        
    ,max(updateStamp)   AS  MaxUpdateStamp
from 
    features
group by 
    feature_area
)
select
    Features.*
from
    Features
inner join 
    Maxfeature
on
    Features.feature_area = MaxFeature.feature_area
and
    Features.updateStamp = MaxFeature.MaxUpdateStamp
order by    
    Features.feature_area asc

答案 3 :(得分:0)

假设有适当的索引,通过反连接来解决这个问题通常是最有效的:

SELECT f1.*
FROM features f1
LEFT JOIN features f2
  ON f2.feature_area = f1.feature_area
  AND f2.updateStamp < f1.updateStamp
WHERE f1.feature_area < 3
  AND f2.id IS NULL
ORDER BY f1.feature_area

如果有重复的行具有相同的feature_area和最高的updateStamp,则会返回重复的行。

有关此技术的更多说明: Get records with highest/smallest <whatever> per group