SQL - 连接没有公共列的表

时间:2016-05-18 19:23:36

标签: sql syntax firebird

这是新的,所以任何提示都将不胜感激!

我有以下查询,我需要的最后一点数据是引入CONTACT.DATUS。问题是CONTACT表与我已经使用的任何表没有任何共同之处(我知道)。我可以通过表格SO - >链接它们。客户 - >联系,但如果有可能,我没有丝毫想法。你可以在最后一次加入时看到我试图这样做但显然这不会起作用。

感谢您帮助我们发送信息!

short

1 个答案:

答案 0 :(得分:1)

现在,您似乎会撤回客户的所有联系人。我假设客户是公司(例如Acme Inc.),而联系人是Acme Inc的员工(Bugs Bunny,Daffy Duck等......)。除非你在联系人表格上有某种标志,表明你想要回复哪个联系人,否则你当前联系上的JOIN会吸引所有人,并且可能会为每个联系人创建一个重复的行。

您的JOIN逻辑非常接近但看起来您跳过了一步: 在您加入联系之前,您需要加入客户。现在,它只是被抛入你的JOIN条款;明确地做。

Select DISTINCT
 so.num AS Ref
, so.shiptoname AS Recipient_Full_Name
, so.shiptoaddress AS Address_1
, so.shiptocity AS City
, stateconst.name AS State
, so.shiptozip AS Zip
, so.billtoname AS Buyer_Name
, contact.datus AS Buyer_Email
, qbclass.name AS Class
, carrier.name AS Carrier
, CAST(soitem.datescheduledfulfillment as date) AS Fulfillment_Date
, contacts.DATUS AS DATUS
From SO
JOIN stateconst
ON so.shiptostateid=stateconst.id
JOIN qbclass
ON so.qbclassid=qbclass.id
JOIN soitem
ON so.id=soitem.soid
JOIN carrier
ON so.carrierid=carrier.id
--My Change--
JOIN customer
ON so.customerid = customer.id
JOIN contact
--Removed this ON so.customerid=customer.id--
ON customer.accountid=contact.accountid
--Done My Change--
WHERE CAST(soitem.datescheduledfulfillment as date) = '5/16/16'
AND qbclass.name<>'C- Online' AND qbclass.name<>'InterCompany'

你的加入并不是所有人都需要基于你的起点,所以。在这种情况下,从SO开始,然后在SO.customerid = Customers.ID上加入客户,然后在Customers.accountid = Contacts.accountid上加入联系人。同样,请注意,这将撤回任何与您的客户共享AccountID的联系人。