合并/加入SQL选择查询

时间:2012-10-15 18:40:54

标签: sql select join merge

我正在努力结合下面的Select Statments,我知道我可以作弊并添加一些假列然后使用Union,但我想要正确地做到这一点。 一旦我加入它们,我将把Statment放入XML文件中,以便与Word和CRM4一起使用。

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的公共列,我也需要在某处添加。

2 个答案:

答案 0 :(得分:1)

您可以在表格上使用LEFT JOIN

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

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

你可以把JOINing想象成并排排在一起的行,而UNIONing正在将行排在第一行之上。 UNIONS要求列相同,JOIN要求每行之间存在某种关系。

编辑 - OP提供了更多详细信息