2012-10-15 134 views
1

我正在努力結合下面的Select Statements,我知道我可以作弊並添加一些虛假的列然後使用Union,但我想正確地做到這一點。 一旦我將他們加入,我將把這個陳述放入一個用於Word和CRM4的XML文件中。合併/加入SQL選擇查詢

SELECT BILLTO_NAME, 
     BILLTO_LINE1, 
     BILLTO_LINE2, 
     BILLTO_LINE3, 
     BILLTO_CITY, 
     BILLTO_COUNTRY, 
     BILLTO_POSTALCODE, 
     ORDERNUMBER, 
     REQUESTDELIVERYBY, 
     MODIFIEDON, 
     SHIPTO_NAME, 
     SHIPTO_LINE1, 
     SHIPTO_LINE2, 
     SHIPTO_LINE3, 
     SHIPTO_CITY, 
     SHIPTO_STATEORPROVINCE, 
     SHIPTO_COUNTRY, 
     SHIPTO_POSTALCODE, 
     CREATEDBY 
FROM SALESORDERBASE 



SELECT QUANTITY, 
     DESCRIPTION 
FROM SALESORDERDETAILBASE 

SELECT NEW_ORDERNOTES, 
     NEW_NOTES 
FROM SALESORDEREXTENSIONBASE 

它們都具有SalesOrderID的公共列,我需要在某處添加它。

回答

1

您可以在表上使用LEFT JOIN的OP:

SELECT ob.SalesOrderID 
     ob.BILLTO_NAME, 
     ob.BILLTO_LINE1, 
     ob.BILLTO_LINE2, 
     ob.BILLTO_LINE3, 
     ob.BILLTO_CITY, 
     ob.BILLTO_COUNTRY, 
     ob.BILLTO_POSTALCODE, 
     ob.ORDERNUMBER, 
     ob.REQUESTDELIVERYBY, 
     ob.MODIFIEDON, 
     ob.SHIPTO_NAME, 
     ob.SHIPTO_LINE1, 
     ob.SHIPTO_LINE2, 
     ob.SHIPTO_LINE3, 
     ob.SHIPTO_CITY, 
     ob.SHIPTO_STATEORPROVINCE, 
     ob.SHIPTO_COUNTRY, 
     ob.SHIPTO_POSTALCODE, 
     ob.CREATEDBY, 
     od.QUANTITY, 
     od.DESCRIPTION, 
     oe.NEW_ORDERNOTES, 
     oe.NEW_NOTES 
FROM SALESORDERBASE ob 
LEFT JOIN SALESORDERDETAILBASE od 
    on ob.SalesOrderID = od.SalesOrderID 
LEFT JOIN SALESORDEREXTENSIONBASE oe 
    on ob.SalesOrderID = oe.SalesOrderID 
+0

謝謝你們,我想這是一個加入我需要的,但不能肯定的是,我對SalesOrderBase和SalesOrderDetailBase都有一個Description列的事實存在一些小問題,我想我可以拿出一個。有沒有人對我可以閱讀的SQL書有任何建議? Ry –

+0

@RyanKeen你需要做的就是爲這些字段提供一個別名。那麼你應該沒有問題從兩列中返回數據。 :) – Taryn

+0

非常感謝您的幫助。 –

0

假設標識的關係被稱爲ID在所有三個表的列,你可以這樣做:

SELECT sob.BILLTO_NAME, 
    sob.BILLTO_LINE1, 
    sob.BILLTO_LINE2, 
    sob.BILLTO_LINE3, 
    sob.BILLTO_CITY, 
    sob.BILLTO_COUNTRY, 
    sob.BILLTO_POSTALCODE, 
    sob.ORDERNUMBER, 
    sob.REQUESTDELIVERYBY, 
    sob.MODIFIEDON, 
    sob.SHIPTO_NAME, 
    sob.SHIPTO_LINE1, 
    sob.SHIPTO_LINE2, 
    sob.SHIPTO_LINE3, 
    sob.SHIPTO_CITY, 
    sob.SHIPTO_STATEORPROVINCE, 
    sob.SHIPTO_COUNTRY, 
    sob.SHIPTO_POSTALCODE, 
    sob.CREATEDBY, 
    sodb.QUANTITY, 
    sodb.DESCRIPTION, 
    soeb.NEW_ORDERNOTES, 
    soeb.NEW_NOTES 
From SalesOrderBase sob 
JOIN SalesOrderDetailBase sodb 
    ON sob.id = sodb.SalesOrderID 
JOIN SalesOrderExtensionBase soeb 
    ON sob.id = soeb.SalesOrderID 

你能想到的加盟爲行砰一起並排側,而UNIONing被砰的一起排在另一排之上。 UNION要求列是相同的,JOIN要求每行之間有某種關係。

編輯 - 提供更多的細節

+0

感謝您的幫助:-) –