简体   繁体   English

使用优先级字段获取已连接的mysql表上的最大值/最小值

[英]Get maximum/minimum values on joined mysql tables with priority field

I have three tables to describe jobs that have tasks: 我有三个表来描述具有任务的作业:

job:
jobId (int)
name (varchar)

task:
taskId (int)
jobId (int)
statusId (int)
name

taskStatus:
taskStatusId (int)
name (varchar)
priority (int)

I want to present the user with a list, that shows every jobs, and in the list, I need to show the name and status of the task with the highest and lowest priority. 我想向用户显示一个列表,该列表显示每个作业,并且在列表中,我需要显示优先级最高和最低的任务的名称和状态。 For example: 例如:

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

I am using MySQL and so far all I could come up was to use triggers to query and store the name and status of the highest and lowest tasks for every job in the jobs table, but I would like to solve this in the select query, if that's possible. 我正在使用MySQL,到目前为止,我所能做的就是使用触发器来查询并存储作业表中每个作业的最高和最低任务的名称和状态,但是我想在选择查询中解决此问题,如果可能的话。

Any suggestions? 有什么建议么? Thanks 谢谢

One way to approach this is with nested scalar subqueries: 解决此问题的一种方法是使用嵌套标量子查询:

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;

This is likely to result in the best performance, if you have the appropriate indexes: task(jobid, name) , taskstatus(name, priority, status) . 如果您具有适当的索引,则这有可能导致最佳性能: task(jobid, name)taskstatus(name, priority, status)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM