測試一下你的T-SQL基礎知識-subquery

一直覺得本身SQL挺好的,沒有想到今天在重構存儲過程遇到了一個子查詢的問題,修改成自鏈接以後發現竟然結果不對,因而有了下面的測試。假設表中有以下數數據,請問Query1,Query2,Query3的查詢結果?ide

ID   OrderID TransID Type
1 1 1 E
2 1 1 A
3 1 1 B
4 1 2 A
5 1 2 B
6 2 1 A
7 2 1 B
8 2 2 A

 

--Query 1
SELECT * FROM OrderDetail a
left join OrderDetail b ON a.OrderID=b.OrderID and a.TransID=b.TransID and b.Goods='E'
WHERE b.Goods is  null

--Query 2
SELECT * FROM OrderDetail a
WHERE a.TransID <>
(
   SELECT top 1 b.TransID FROM OrderDetail b WHERE b.OrderID=a.OrderID and b.Goods='E'
)

--Query 3
SELECT * FROM OrderDetail a
WHERE NOT EXISTS 
(
    SELECT  b.TransID,b.orderid  FROM OrderDetail b WHERE b.OrderID=a.OrderID and b.Goods='E'
)

在查看運行結果前請默默的寫下您的答案:
Query1測試

ID    OrderID    TransID    Goods
4    1    2    A
5    1    2    B
6    2    1    A
7    2    1    B
8    2    2    A
View Code

Query2spa

ID    OrderID    TransID    Goods
4    1    2    A
5    1    2    B
View Code

Query3code

ID    OrderID    TransID    Goods
6    2    1    A
7    2    1    B
8    2    2    A
View Code
相關文章
相關標籤/搜索