两个简单的表格
基础表
+--------+
|id|value|
+--------+
| | |
+--------+
事件表(包含大量数据..)
+--------------+
|id|event| date|
+--------------+
| | | |
+--------------+
然后我想要一个所有 base.value 的列表,与最后 事件相对应(包括没有事件条目的值)
+----------------+
|id|lastEvt|value|
+----------------+
| | | |
+----------------+
这是一个(工作但是)非常缓慢的尝试
SELECT *
FROM (
SELECT base.id,
event.event,
base.value
FROM base
LEFT OUTER JOIN event
ON base.id = event.id
ORDER BY event.date DESC
)
AS res
GROUP BY res.id;
我怀疑有更好/更快的方式来进行查询,但我不知道如何...
答案 0 :(得分:4)
SELECT b.id, b.value, e.event
FROM base b
LEFT JOIN (SELECT id, MAX(date) AS LastEventDate
FROM event
GROUP BY id) q
INNER JOIN event e
ON q.id = e.id
AND q.LastEventDate = e.date
ON b.id = q.id
答案 1 :(得分:1)
SELECT
b.id, b.value, e.event
FROM Base b
LEFT JOIN Event e ON (b.id = e.id)
ORDER BY e.date DESC
GROUP BY b.id
我假设你在这两个表上都有适当的索引。
答案 2 :(得分:0)
也许我错过了什么,但似乎这应该有效:
SELECT base.id,
base.value,
event.date
FROM
base
LEFT OUTER JOIN
event ON base.id = event.id
ORDER BY event.date DESC
GROUP BY base.id
至于上面的查询是否更快,我认为这是因为它不包含任何子查询,但是你必须进行基准验证。