mysql>复杂 ORDER by 查询的帮助
我不是 SQL 专家,所以我在这里请求有关以下情况的一些帮助:
我有 2 个表; 1 个表“任务”(ID,TITLE,CREATEDAT)
和 1 个表“活动”(ID,TASK_ID,TITLE,CREATEDAT)
,其中 CREATEDAT
是一个 DATETIME
列。
我想在任务和活动中列出按最后一个 CREATEDAT
列排序的任务!我的意思是,有最近的任务(CREATEDAT
AND
其中有最近的活动,例如任务和活动表的联合...),但我真的没有想法如何处理?
感谢您的帮助!
I am not an expert on SQL, so I am asking here some help about the following case :
I have 2 tables; 1 table "task" (ID,TITLE,CREATEDAT)
and 1 table "activity" (ID,TASK_ID,TITLE,CREATEDAT)
where CREATEDAT
are a DATETIME
column.
I would like to list the tasks ordering by last CREATEDAT
column, in task and activity! I mean, have the most recent task (CREATEDAT
AND
which have the most recent activity, such an union of task & activity table...) but I have really no idea of how to process?
Thanks you for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果任务没有活动,则按最近活动或创建日期对任务进行排序:
To order tasks by most recent activity or creation date if there is no activity on the task:
我认为这就是您正在寻找的,如果您想显示所有任务,即使它们没有活动。
编辑:我将提供一个简短的解释,可能会帮助您了解更多。
该语句基本上告诉数据库获取任务表和活动表中特定列“id”和“title”中的所有信息 - 这是
sekect task.id、task.title、activity.id, Activity.title
子句。任何查询都将始终使用
from
关键字搜索至少一个表。在本例中,我们使用了from task
,它将搜索任务表。但是,对于此示例,您需要两个表的并集,需要使用join
关键字。使用join
允许我们以多种方式搜索多个表。在本例中我们使用了左连接
;如果您想对此进行进一步解释,请发表评论。最后,我们简单地按任务创建日期、活动创建日期对数据进行排序,并指定降序(最早的在前,最新的在后)。
请注意,一般情况下,使用
select *
不是最好的主意。它现在可能满足您的需求,但如果您要构建更多查询,您将需要指定要显示的列,如我的示例中所示。I think this is what you're looking for, if you want to show all tasks even if they don't have activities.
edit: I'll provide a short explanation that might help you understand a little more.
This statement basically tells the database to grab all the information in the specific columns "id" and "title" in the task table and the activity table - this is the
sekect task.id, task.title, activity.id, activity.title
clause.Any query will always search at least one table, using the
from
keyword. In this case, we usedfrom task
, which would search the task table. However, for this example, you needed a union of two tables, requiring the use of thejoin
keyword. Usingjoin
allows us to search more than one table, in multiple ways. We used aleft join
in this case; comment if you'd like a further explanation about this.Finally, we simply ordered the data by the task creation date, and then the activity creation date, and specified descending order (oldest first, newest last).
Note that, in general, using
select *
isn't the best idea. It may satisfy your needs now, but if you're going to build more queries, you'll want to specify the columns you want to display, as in my example.