2013-06-24 46 views
0

我有以下SQL 2個不同的參數:的MySQL/PHP - 1個表

$queryString = " 
      SELECT  
       iR.lastModified, 
       d.*, 
       c2.title as stakeholderTitle, 
       u.username as authorUsername, 
       c.title as authorContactName, 
       GROUP_CONCAT(iR.stakeholderRef) AS participants 
      FROM 
       informationRelationships iR, 
       contacts c2 
      INNER JOIN 
       debriefs d ON 
       d.id = iR.linkId 
      LEFT JOIN 
       users u ON 
       u.id = iR.author  
      LEFT JOIN 
       contacts c ON 
       c.ref = u.contactId 
      LEFT JOIN 
       debriefs d2 ON 
       d2.stakeholder = c2.ref     
      WHERE    
       ( 
        iR.clientRef = '$clientRef' OR 
        iR.contactRef = '$contactRef' 
       ) 
       AND  
        iR.projectRef = '$projectRef' AND 
        iR.type = 'Debrief' 
      GROUP BY 
       iR.linkId 
      ORDER BY 
       d.dateOfEngagement      
     ";  

通知我如何要求對聯繫人表數據的2個不同的位。

因此,在一個點上,我需要匹配

c.ref = u.contactId 

這將返回的信息

一位,但我也需要一個完全不同的分組:

d2.stakeholder = c2.ref 

問題是,標題是我對這兩方面感興趣的專欄:

c2.title as stakeholderTitle, 
... 
c.title as authorContactName 

我該如何去做這件事?

我現在嘗試將返回:

Error: Unknown column 'iR.linkId' in 'on clause' 

enter image description here

我不知道我真正明白髮生了什麼這裏:

how to join two tables on common attributes in mysql and php?

編輯:::: --- ANSWERED - zerkms

$queryString = " 
     SELECT  
      iR.lastModified, 
      d.*, 
      c2.title as stakeholderTitle, 
      u.username as authorUsername, 
      c.title as authorContactName, 
      GROUP_CONCAT(iR.stakeholderRef) AS participants 
     FROM 
      informationRelationships iR    
     INNER JOIN 
      debriefs d ON 
      d.id = iR.linkId 
     INNER JOIN 
      contacts c2 ON 
      d.stakeholder = c2.ref 
     LEFT JOIN 
      users u ON 
      u.id = iR.author  
     LEFT JOIN 
      contacts c ON 
      c.ref = u.contactId    
     WHERE    
      ( 
       iR.clientRef = '$clientRef' OR 
       iR.contactRef = '$contactRef' 
      ) 
      AND  
       iR.projectRef = '$projectRef' AND 
       iR.type = 'Debrief' 
     GROUP BY 
      iR.linkId 
     ORDER BY 
      d.dateOfEngagement      
    ";  

通過重新排序我的查詢我設法得到兩列在...謝謝zerkms!

+0

它清楚地表明informationRelationships不包含名爲linkId的列。你能描述桌子嗎? – chetan

回答

0

你不能在mysql中的單個查詢中混合隱式連接和顯式連接。

所以

FROM informationRelationships iR, 
    contacts c2 

應該重寫

FROM informationRelationships iR 
INNER JOIN contacts c2 ON ... 
+0

AHHH我明白了,所以實際上我現在只需要你寫下這個的一個加入。爲什麼我以前沒有看到這個!哎呀,你必須小心,不要你! – Jimmyt1988

+0

@詹姆斯T:「你必須小心不要你」---是的,但是如果mysql拋出一些有意義的錯誤,而不僅僅是混淆「未知列」 – zerkms

0

不要使用笛卡爾乘積,並在同一個查詢連接(不是子查詢),在這裏,只用連接(CROSS JOIN是一樣的作爲笛卡爾產品)。

+0

「不要使用笛卡爾積和加入相同的查詢「---這不夠清楚。請說明 – zerkms

+0

'FROM informationRelationships iR CROSS JOIN聯繫人c2 ON 1 = 1 INNER JOIN彙總d ON d.id = iR.linkId ...'而不是'FROM informationRelationships iR,聯繫人c2 INNER JOIN彙報d ON d.id = iR。 linkId ...' –

+0

「不要使用笛卡爾產品並加入」---但你建議使用笛卡爾產品並加入,不是嗎?;-) – zerkms