获取带有优先级字段的连接 mysql 表的最大值/最小值



我有三个表格来描述有任务的作业:

job:
jobId (int)
name (varchar)
task:
taskId (int)
jobId (int)
statusId (int)
name
taskStatus:
taskStatusId (int)
name (varchar)
priority (int)

我想向用户显示一个列表,其中显示了每个作业,并且在列表中,我需要显示具有最高和最低优先级的任务的名称和状态。例如:

Job                 Highest priority task     Highest pri. task status
Build a house          Build the base              Very high

正在使用MySQL,到目前为止,我所能想到的就是使用触发器来查询和存储作业表中每个作业的最高和最低任务的名称和状态,但如果可能的话,我想在选择查询中解决这个问题。

有什么建议吗?谢谢

解决此问题的一种方法是使用嵌套标量子查询:

select j.name,
       (select ts.name
        from task t join
             taststatus ts
             on t.name = ts.name
        where t.jobid = j.jobid
        order by priority
        limit 1
       ) as HighestPriority,
       (select ts.status
        from task t join
             taststatus ts
             on t.name = ts.name
        where t.jobid = j.jobid
        order by priority
        limit 1
       ) as HighestPriorityStatus
from job j;

如果您有适当的索引,这可能会导致最佳性能:task(jobid, name)taskstatus(name, priority, status)

最新更新