我的应用程序的一部分由一个讨论板组成:有主题、帖子和类别。主题按类别分组,帖子按主题分组。我在提出一个模型/查询时遇到问题,该模型/查询将允许按类别选择线程,并按其上一篇文章的降序排列。
类别
CREATE TABLE keyspace.categories (
id ascii PRIMARY KEY,
description text,
name text,
...
);
线
CREATE TABLE keyspace.threads (
id ascii PRIMARY KEY,
category_id ascii,
content text,
...
);
邮政
CREATE TABLE keyspace.posts (
thread_id ascii,
created_at timestamp,
id ascii,
content text,
...
PRIMARY KEY (thread_id, created_at, id)
);
我最初考虑将最后一个帖子的“创建时间”作为线程表上的集群键,但这是不可能的,因为它随着每个帖子的变化而变化。
然后我考虑创建一个中间表,每次创建帖子时都会写入该表。这解决了第一种方法的不变性问题,但问题是每个线程将包含多个值,我无法找出支持按线程分组和按日期排序的分区/集群顺序。
例如,以下内容将允许我按线程分组,但不能按日期排序:
CREATE TABLE last_post_for_category (
category_id ascii,
thread_id ascii,
created_at timestamp,
PRIMARY KEY ((category_id), thread_id, created_at)
) WITH CLUSTERING ORDER BY (thread_id DESC, created_at DESC);
SELECT thread_id FROM last_post_for_category WHERE category_id = 'category' GROUP BY thread_id, created_at;
以下将允许我按日期订购,但不能按线程分组:
CREATE TABLE keyspace.last_post_for_category (
category_id ascii,
thread_id ascii,
created_at timestamp,
PRIMARY KEY ((category_id), created_at, thread_id)
) WITH CLUSTERING ORDER BY (created_at DESC, thread_id DESC);
SELECT thread_id FROM last_post_for_category WHERE category_id = 'category' GROUP BY created_at, thread_id;
我不能做一个distinct
对(category_id, thread_id)
无论是作为我知道在其中执行此查询点一无所知线程ID。
有没有人知道我如何最好地代表这个顺序?
首先,我建议您使用数据类型datetime
而不是timestamp
,因为这样可以方便您修改它或设置默认值。这只是一个建议。
建议的解决方案:
将该属性添加last_post
到表中threads
以保存每个线程中最后添加帖子的时间。
首次创建线程时,该last_post
值应等于一个非常旧的日期(因为该线程中还没有帖子)。
之后,创建一个触发器,以便每当在 中插入帖子时posts
,触发器都会更新last_post
相应线程的值。触发器可以这样添加:
CREATE TRIGGER triggerName ON posts
FOR INSERT
AS
declare @post_time datetime;
declare @thread_id int;
select @post_time=i.created_at from inserted i;
select @thread_id=i.thread_id from inserted i;
update threads set lastpost = @post_time where id=@thread_id
GO
最后一步将是直接查询以按类别排序选择线程last_post
,就像这样:
select * from threads where category_id = 'theCategoryYouWant' order by lastpost asc /*or desc as you like*/
注意:如果你想created_at
在编辑帖子时更新,你需要添加一个类似的触发器来更新last_post
对应线程的属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句