2016-08-05 103 views
0

我正在嘗試將聯繫人(T.ContactId)查找添加到現有查詢中。該查詢使用客戶端ID從客戶端表中獲取客戶端。我現在希望添加T.ContactId以獲取客戶表中的另一個名稱。在下面的腳本我已經添加了「T.ContactId」的選擇,但我不知道如何從那裏繼續MYSQL - 從多列表查詢中的一列中選擇兩次

  select T.Id Tid,Transdate,Quantity Unit,Amount Rate,Discount,T.Comment Comment,T.CmntToInvoice ConInv,T.JobNum JobNum,T.PayNum PayNum,T.ContactId,clients.Id `Id`,`Client`,Cell,Email,Yard,Horse,TransType `Transaction`,PayTypeId,Credit 
     from 
      transactions T,clients,yards,horses,transtypes 
     where 
      Pending = 'N' and 
      T.TransTypeId = transtypes.Id and 
      T.ClientId = clients.Id and 
      T.HorseId = horses.Id and 
      T.YardId = yards.Id and 
      Transdate between '2014-09-08' and '2016-07-08' and 
      T.JobNum = 0 
     order by 
      clients.Id,Transdate asc 
+0

所以T.ContactId在選擇查詢中存在,現在只需運行腳本,並且如果您希望T.ContactId查看您的代碼中使用PayNum –

+0

sry,但這沒有幫助,因爲它無法在該查詢中找到聯繫人和客戶端因爲它是...如果它可以你會顯示如何? – Dave

回答

1

你應該改變你的隱加入到明確連接,並添加第二個連接獲取客戶端對於t.contactid ID等試試這個

select T.Id Tid,Transdate,Quantity Unit,Amount Rate,Discount,T.Comment Comment,T.CmntToInvoice ConInv,T.JobNum JobNum,T.PayNum PayNum, 
      T.ContactId,c1.id as 'ccid',c1.client as 'ContactCLient', 
      clients.Id `Id`,`Client`,Cell,Email,Yard,Horse,TransType `Transaction`,PayTypeId,Credit 
from transactions T 
join   clients on T.ClientId = clients.Id 
join  yards on T.YardId = yards.Id 
join   horse on T.HorseId = horses.Id 
join   transtypes on T.TransTypeId = transtypes.Id 
left outer join clients c1 on c1.id = t.contactid 
where  Pending = 'N' and 
      Transdate between '2014-09-08' and '2016-07-08' and 
      T.JobNum = 0 
order by clients.Id,Transdate asc 

我沒有測試過這一點,但如果你能發佈樣本數據和預期結果的話,我會很樂意重新審視。

+0

它工作得很好,經過一些調整後得到我想要的東西:) – Dave