使用join

时间:2019-05-13 01:42:49

标签: sql tsql

我是SQL的新手,只是一个关于delete语句的问题,假设我们在DML查询下面:

DELETE FROM O
FROM dbo.Orders AS O
JOIN dbo.Customers AS C ON O.custid = C.custid
WHERE country = N'Brazil';

我不明白为什么它首先是FROM关键字,难道像这样:

DELETE O
FROM dbo.Orders AS O
JOIN dbo.Customers AS C ON O.custid = C.custid
WHERE country = N'Brazil';

因为其他一些DML语句(如“更新”),语法为:

UPDATE OD   // no 'from'
SET discount += 0.05
FROM dbo.OrderDetails AS OD
JOIN dbo.Orders AS O ON OD.orderid = O.orderid
WHERE O.custid = 1;

没有类似的东西:

UPDATE FROM OD ...
...

1 个答案:

答案 0 :(得分:1)

第一个FROMdelete中是可选的。我将其写为:

DELETE O
FROM dbo.Orders O JOIN
     dbo.Customers C
     ON O.custid = C.custid
WHERE country = N'Brazil';

也就是说,O中的DELETE OFROM中定义的别名。

UPDATE也是如此。

SQL Server恰好支持:

DELETE dbo.Orders
FROM dbo.Orders O JOIN
     dbo.Customers C
     ON O.custid = C.custid
WHERE country = N'Brazil';

在这种情况下,dbo.OrdersO引用的表“相同”。我认为这是非常糟糕的形式,因为它与所有其他SQL语句中的别名定义不一致。