MYSQL - 在多表查询中从一列中选择两次

时间:2016-08-05 09:23:40

标签: mysql

我正在尝试向现有查询添加联系人(T.ContactId)查找。该查询使用客户端ID从clients表中获取客户端。我现在希望添加T.ContactId以从clients表中获取另一个名称。在下面的脚本中,我已经添加了' T.ContactId'选择,但我不知道如何从那里继续

            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

1 个答案:

答案 0 :(得分: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

我没有对此进行测试,但如果您可以发布样本数据和预期结果,那么我很乐意再次访问。

相关问题