试图改进SQL查询输出

时间:2013-03-06 20:47:12

标签: mysql sql

我在创建查询时遇到问题。以下是我的想法:

SELECT sitedata.sitecode       Site, 
       projectdata.startdate   Start, 
       projectdata.enddate     End, 
       resourcedata.firstname  PM_Name, 
       resourcedata.firstname  Lead_Name, 
       rresourcedata.firstname Other_Name 
FROM   projectdata 
       JOIN sitedata 
         ON projectdata.siteid = sitedata.id 
       JOIN resourcedata 
         ON projectdata.pmid = resourcedata.id 
             OR projectdata.leadid = resourcedata.id 
             OR projectdata.otherid = resourcedata.id 
WHERE  startdate = '03/06/2013' 

我查询中的当前输出如下:

Site   PM_Name   Lead_Name   Other_Name   
ST1    Joe       Joe         Joe
ST1    Jim       Jim         Jim
ST1    Bill      Bill        Bill
ST2    Lee       Lee         Lee
ST2    Jim       Jim         Jim
ST2    Bill      Bill        Bill

以下是我想要获得的输出:

Site   PM_Name   Lead_Name    Other_Name   
ST1    Jim       Joe          Bill
ST2    Bill      Lee          Jim

2 个答案:

答案 0 :(得分:1)

您需要3个单独的JOINS:

SELECT sitedata.sitecode       Site, 
       projectdata.startdate   Start, 
       projectdata.enddate     End, 
       pm.firstname  PM_Name, 
       ld.firstname  Lead_Name, 
       on.firstname Other_Name 
FROM   projectdata 
       JOIN sitedata ON projectdata.siteid = sitedata.id 
       LEFT JOIN resourcedata pm ON projectdata.pmid = resourcedata.id 
       LEFT JOIN resourcedata ld ON projectdata.leadid = resourcedata.id 
       LEFT JOIN resourcedata on ON projectdata.otherid = resourcedata.id 
WHERE  startdate = '03/06/2013'

我使用了LEFT JOIN,以防某些角色未分配(NULL),如果您确定不是这种情况,则可以继续使用INNER JOIN。

答案 1 :(得分:0)

您需要做的是为您正在寻找的每个名称加入3次资源表...

SELECT 
      sitedata.sitecode       Site, 
      projectdata.startdate   Start, 
      projectdata.enddate     End, 
      PM.firstname  PM_Name, 
      LEAD.firstname  Lead_Name, 
      OTHER.firstname Other_Name 
   FROM   
      projectdata 
         JOIN sitedata 
            ON projectdata.siteid = sitedata.id 
         JOIN resourcedata as PM
            ON projectdata.pmid = PM.id 
         JOIN resourcedata LEAD
            ON projectdata.leadid = LEAD.id 
         JOIN resourcedata OTHER
            ON projectdata.otherid = OTHER.id 
   WHERE  
      startdate = '03/06/2013'