GROUP BY 之后应用 WHERE
我有一个表,其中包含属于线程一部分的项目,因此它们有一个线程 ID,每个项目还有一个日期(UNIX 时间戳)。我的表如下所示(简化的 UNIX 时间戳):
+-----------------------------+
| id | date | thread_id |
+-----+---------+-------------+
| 1 | 1111 | 4 |
| 2 | 1333 | 4 |
| 3 | 1444 | 5 |
| 4 | 1666 | 5 |
+-----------------------------+
我想要做的是选择线程 ID,其中共享同一线程 ID 的所有项目都小于传递的日期。因此,如果我想要所有项目都早于 1555
(日期 <1555
)的线程 ID
,我只希望有线程ID 4,而不是
5
,即使它的项目的日期小于 1555
。这就是我尝试过的:
SELECT * FROM table WHERE date < 1555 GROUP BY thread_id ORDER BY date DESC
我尝试对该查询执行的操作是按具有最高日期值的项目周围的线程 ID 对所有项目进行分组,并从那里获取日期小于 1555
。但这不起作用,它仍然会返回线程 ID 5
,因为它有一个早于 1555
的项目。
总而言之,我如何只选择所有项目都早于某个日期的线程 ID?
I have a table with items that are part of a thread, so they have a thread ID, each item also has a date (UNIX timestamp). My table looks something like the following (UNIX timestamps simplified):
+-----------------------------+
| id | date | thread_id |
+-----+---------+-------------+
| 1 | 1111 | 4 |
| 2 | 1333 | 4 |
| 3 | 1444 | 5 |
| 4 | 1666 | 5 |
+-----------------------------+
What I want to do is select thread IDs
where ALL the items sharing the same thread ID are smaller than the passed date. So if I wanted thread IDs
where ALL items are older than 1555
(date < 1555
), I would only expect to have thread ID 4
returned, not 5
even though it's got an item with a date smaller than 1555
. This is what I tried:
SELECT * FROM table WHERE date < 1555 GROUP BY thread_id ORDER BY date DESC
What I'm trying to do with that query is group all items by thread ID around the item with the highest date value and from there get the items where the date is less than 1555
. But that doesn't work, it will still return thread ID 5
because it's got an item older than 1555
.
So to summarize, how would I only select thread IDs
where ALL items are older than a certain date?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 HAVING 子句。这允许您过滤 SUM、MAX 等聚合...在这里,您只想选择最新条目早于 1555 的线程 id,因此您可以编写:
Use a HAVING clause. This allows you to filter on aggregates like SUM, MAX... Here you want to select only those thread id's whose newest entry is older than 1555, so you write:
您可以使用
having
代替where
:You can use
having
in place ofwhere
: