我有两张桌子e和o1
表e
具有
Onumber edt_image
1 AA
1 AB
1 AC
1 AA
1 AB
2 AB
3 AB
3 AA
表o1
有
Onumber Obill
1 ABCD
2 ABCD
3 ABCD
所以,当我希望sql拉我Onumber没有AA和obill“ABCD”时,我的意思是
Onumber edt_image
2 AB
但是现在它拉我了
Onumber Edt_image
1 AB
1 AC
1 AB
2 AB
3 AB
我使用的sql
Select e.onumber,o1.onumber
From e join o1 on o1.onumber=e.onumber
Where e.edt_image<>’AA’
And o1.obill=ABCD
答案 0 :(得分:0)
使用EXISTS
和NOT EXISTS
:
SELECT *
FROM e e1
WHERE NOT EXISTS(SELECT 1 FROM e
WHERE Onumber = e1.Onumber
AND edt_image = 'AA')
AND EXISTS( SELECT 1 FROM o1
WHERE Onumber = e1.Onumber
AND Obill = 'ABCD');
答案 1 :(得分:0)
试试这个。希望能帮助到你。
如果您在较大的结果集上运行查询,请考虑在连接键上添加索引。
请注意,请在添加任何索引之前查看对服务器的较大影响
;WITH cte_e (Onumber,edt_image) AS
(
SELECT 1, 'AA' UNION ALL
SELECT 1, 'AB' UNION ALL
SELECT 1, 'AC' UNION ALL
SELECT 1, 'AA' UNION ALL
SELECT 1, 'AB' UNION ALL
SELECT 2, 'AB' UNION ALL
SELECT 3, 'AB' UNION ALL
SELECT 3, 'AA'
), cte_O1(Onumber, Obill) AS
(
SELECT 1, 'ABCD' UNION ALL
SELECT 2, 'ABCD' UNION ALL
SELECT 3, 'ABCD'
)
SELECT e1.onumber,
e1.edt_image
FROM cte_e e1
INNER JOIN cte_O1 o1
ON o1.Onumber = e1.Onumber
WHERE NOT EXISTS (
SELECT 1
FROM cte_e e2
WHERE e1.Onumber = e2.Onumber
AND edt_image = 'AA'
)