我得到了兩個表,訂單有兩列作爲orderid和customerid,以及有兩列作爲customerid和location的客戶。與SqlServer,其中*不存在
我想要做的是在表Customers中找到所有customerid,它們不在Orders中。例如,Customers.customerid = {A,B,C,D},Orders.customerid = {A,B,C},我想要做的只是從客戶那裏獲取,而不是在訂單中存在。爲了實現這一點,我說,
select customerid from Customers where customerid not exists (select customerid from Orders)
但它沒有返回。我的邏輯是相當簡單的像,第一次拿到表中所有訂單客戶ID,然後得到它不會在customerIds從表Orders exisit的那些。我看不出爲什麼這是錯誤的。
我以後試過,它工作。任何人都可以幫助我嗎?
select customerid from Customers as c where customerid not exists(select customerid from orders as o where c.customerid = o.customerid)
爲什麼我必須添加c.customerid = o.customerid?
不知道爲什麼SQL Server允許您在沒有任何警告或錯誤的情況下運行這些查詢,但是您的問題非常簡單,您應該在詢問之前閱讀並理解「EXISTS」語句:https://technet.microsoft.com/zh-cn/ -us/library/ms189259(v = sql.105).aspx –