使用不同的critera在同一个表上连接不同的行

时间:2015-10-06 09:50:49

标签: mysql sql join

我试着四处寻找和谷歌搜索,我最终得到一个查询,在任何可能的意义上杀死数据库。

我有3张桌子:

jiraissue保存有关jira票据(分配给谁)的信息。

changegroup这会保留更改日期,更改故障单的ID以及更改详细信息的ID。

changeitem包含更改ID,更改字段和新/旧值。

我想要以下输出:

[time_taken_to_resolve],[assigned_date],[resolve_date],[jira_ticket_details_from_jiraissue]

标准是jiraissue.ASSIGNEE值。

我想出了以下内容:

SELECT TIMESTAMPDIFF(HOUR,a.assigned_date,b.resolved_date),a.*, b.* 
FROM jiraissue 
INNER JOIN (
    SELECT changegroup.CREATED as "assigned_date",changegroup.issueid as jid 
    FROM changegroup 
    JOIN changeitem ON changegroup.ID = changeitem.groupid 
    WHERE changeitem.FIELD="assignee"
    GROUP BY changegroup.issueid 
    ORDER BY changegroup.CREATED DESC 
) as a ON a.jid = jiraissue.id 
INNER JOIN ( 
    SELECT changegroup.CREATED as "resolved_date", changegroup.issueid as jid 
    FROM changegroup 
    JOIN jiraissue on changegroup.issueid = jiraissue.ID 
    JOIN changeitem ON changegroup.ID = changeitem.groupid 
    WHERE changeitem.FIELD="status" AND changeitem.NEWVALUE=5
    GROUP BY changegroup.issueid 
    ORDER BY changegroup.CREATED DESC 
) as b ON b.jid = jiraissue.id 
WHERE jiraissue.ASSIGNEE = "gangsta"; 

如果我使用特定的jiraissue.id,则上述查询有效,但如果我按jiraissue.ASSIGNEE进行搜索(它继续进行运算)则不行。

此外,我对最新解决和分配的日期感兴趣,可能会有很多,但我想要最后一个。

非常感谢任何帮助。

谢谢。

1 个答案:

答案 0 :(得分:0)

想到这一点,似乎可以做到这一点:

SELECT TIMESTAMPDIFF(HOUR,a.assigned_date,b.resolved_date),a.*, b.*,jiraissue.*
FROM jiraissue
INNER JOIN (
  SELECT  MAX(changegroup.CREATED) as "assigned_date",changegroup.issueid as jid
  FROM changegroup 
  JOIN jiraissue as ji1 ON changegroup.issueid=ji1.id 
  JOIN changeitem ON changegroup.ID = changeitem.groupid 
  WHERE changeitem.FIELD="assignee" AND ji1.ASSIGNEE="gangsta" AND issuetype = 5 AND PRIORITY = 4
  GROUP BY changegroup.issueid
) as a ON a.jid = jiraissue.id
INNER JOIN (
  SELECT  MAX(changegroup.CREATED) as "resolved_date", changegroup.issueid as jid
  FROM changegroup 
  JOIN jiraissue as ji2 ON changegroup.issueid=ji2.id 
  JOIN changeitem ON changegroup.ID = changeitem.groupid 
  WHERE changeitem.FIELD="status" AND changeitem.NEWVALUE=5  AND ji2.ASSIGNEE="gangsta" AND issuetype = 5 AND PRIORITY = 4
  GROUP BY changegroup.issueid
) as b ON b.jid = jiraissue.id
ORDER BY b.resolved_date DESC;