SQL Server加入初学者简单连接

时间:2016-10-24 21:11:21

标签: sql sql-server tsql

我有以下两个表:

dbo.orders

  • 客户id
  • 订单ID

dbo.customerprofiletbl

  • 客户id
  • 客户名称

我试图加入一个联接,但我失败了:

select 
    dbo.orders.customerid AS orde, 
    dbo.customerprofiletbl.customerid AS cust
from 
    dbo.customerprofiletbl
left join
    orde on cust 

帮助?

5 个答案:

答案 0 :(得分:0)

您需要做的是:

select 
  orde.customerid AS orde, 
  cust.customerid AS cust
from dbo.customerprofiletbl cust
LEFT JOIN dbo.orders orde on cust.customerid = orde.customerid

您是使用自己创建的表别名(ordecust)从列中获取值,并使用相同的名称调用新列,但这并非如此问题 - 你可以做as OrderCustomerId例如..

加入时,您将一个表连接到另一个表,然后您可以使用表别名来简化操作。当你加入2个表时,你必须告诉它何时用于创建连接的列 - 在这里使用别名帮助。

答案 1 :(得分:0)

你的一些查询有点倒退。您应该将连接表的表名放在join语句中(您仍然可以在那里使用别名),然后在列表中如果选择列,您也可以只使用别名:

SELECT
    orde.customerid,
    cust.customerid
FROM
    dbo.customerprofiletbl cust
LEFT JOIN
    dbo.orders orde
    ON
    cust.customerid = orde.customerid

答案 2 :(得分:0)

select dbo.orders.customerid AS orde, 
  dbo.customerprofiletbl.customerid AS cust
from dbo.customerprofiletbl
LEFT JOIN orde on dbo.customerprofiletbl.customerid  = orde.customerid  

答案 3 :(得分:0)

虽然看起来你的方向错了。但你的查询是这样的    Select o.customerid as orde, cpt.customerid AS cust from dbo.orders o left join dbo.customerprofiletbl cpt on o.customerid=cpt.customerid

CustomerProfiletbl应位于左侧,因为没有客户无法完成订单

答案 4 :(得分:0)

您必须指定进行连接的列 只需添加ON Clause

即可
select 
dbo.orders.orderid
 dbo.customerprofiletbl.customerid
 Dbo.customerprofiletbl.customername
from dbo.customerprofiletbl
    LEFT JOIN dbo.orders ON     dbo.customerprofiletbl.customerid =     dbo.orders.customerid
相关问题