我有以下架构,我很遗憾不允许改变:
+------------+
| vHistory v |
+------------+ +---------------+
| id | | instance i | +----------------------+
| component | +---------------+ | environment e |
| instance |* === 1| id | +----------------------+
| version | | environment |* ===== 1| idEnv |
| date | +---------------+ | environment |
+------------+ +----------------------+
(vHistory
列出中间件上组件的安装日期; instance
列出中间件服务器的实例(例如“Tomcat 6.0.14 on machine”production-server-78“); {{ 1}}表示生产/登台/等)
我想为具有以下列的特定environment
生成一个列表:
v.component
显示每个环境中所选组件的最新安装。我尝试了以下查询:
v.id, v.version, e.environment, v.date
但我觉得使用这两个SELECT MAX(v.id),
e.environment,
v.version,
MAX(nv.date)
FROM vHistory v
INNER JOIN instance i
ON v.instance = i.id
INNER JOIN environment e
ON i.environment = e.idEnv
WHERE v.component = 100
GROUP BY e.environment
函数感觉不太舒服......
有更好的方法吗?我看到this问题加入了日期,但这也让我感到害怕,因为理论上可能会有另一行具有相同的日期。
答案 0 :(得分:1)
我觉得这样的事情会奏效:
SELECT v.id,
e.environment,
v.date
FROM ( SELECT MAX(v2.id) AS id
FROM vHistory v2
INNER JOIN instance i2
ON v2.instance = i2.id
INNER JOIN environment e2
ON i2.environment = e2.idEnv
WHERE v2.component = 100
GROUP BY e2.environment
) AS maxid
JOIN vHistory v
JOIN instance i
JOIN environment e
ON ( maxid.id = v.id
AND v.instance = i.id
AND i.environemnt = e.idEnv
)
maxid仅包含与您的查询匹配的行的最新ID。将这些ID加入整个表格应该只返回您需要的信息。