1

我的 MySQL 数据库有一个表(cfg),其中包含 4 个字段:id、name、data 和 location 这个表用于服务多个子域(location)。我需要获取给定子域(位置)的每个名称的最新行列表。

示例数据

id   name   data   location
---------------------------
1    color  red    dc
2    color  blue   dc
3    size   large  sj
4    color  green  sj
5    size   small  dc

以下查询工作正常,但似乎过于复杂和缓慢。有人有建议吗?

SELECT c1.name, c1.data
FROM (SELECT * FROM cfg WHERE location = "dc") as c1
LEFT JOIN (SELECT * FROM cfg WHERE location = "dc") as c2 ON ( c1.name = c2.name
AND c1.id < c2.id )
WHERE c2.id IS NULL

它会回来

name     data
--------------
color    blue
size     small
4

3 回答 3

2

使用GROUP BY计算最大值的子查询。idname

SELECT cfg.*
FROM   cfg
JOIN  (
    SELECT max(id) AS max_id
    FROM   cfg c0
    WHERE  location = 'dc'
    GROUP  BY name
    ) n ON n.max_id = cfg.id
于 2011-12-23T20:58:42.943 回答
0

我认为

select c.name, c.data
from cfg c
join (
 select max(id) id
 from cfg
 group by name
 where location = 'dc'
) nameMaximums on nameMaximums.id = c.id 

并在 (location, name, id) 上使用索引,在 (id) 上使用索引

于 2011-12-23T21:05:10.270 回答
0
select name, data
from cfg
where id in (select max(id) from cfg where location = "dc" group by name)

这只是未经测试的徒手,但我想你明白了。这假定列 id 是唯一的。

于 2011-12-23T21:05:24.463 回答