只有在其他表中的多行之间不存在某个值时才连接表

时间:2014-01-22 11:03:36

标签: sql sql-server join

我尝试加入两个表。一个是填充了完全唯一变量debtor的表格。不存在重复的债务人ID。 现在,我希望将其加入items表,其中debtor.debtor ID可以多次出现。

我希望只有在订单历史记录中不存在商品'20004'时才加入

我有以下sql小提琴

http://sqlfiddle.com/#!2/a0826/1/0

create table items
 (
 debtor int,
 item int,
 qty int,
 invoice int
 );
create table debtor
 (
 debtor int,
 name varchar(255)
 );
insert into debtor(debtor, name)
VALUES ('1000','Mister blue'),
 ('1001','Mister Orange'),
 ('1002','Mister Red'),
 ('1003','Mister Yellow'),
 ('1004','Mister Green');
INSERT INTO items (debtor, item,qty, invoice)
values ('1000','20001','1','1'),
 ('1000','20002','1','1'),
 ('1000','20003','1','1'),
 ('1000','20004','1','1'),
 ('1000','20005','1','1'),

 ('1001','20001','1','2'),
 ('1001','20002','1','2'),
 ('1001','20003','1','2'),

 ('1001','20005','1','2'),

 ('1002','20001','1','3'),
 ('1002','20002','1','3'),
 ('1002','20003','1','3'),
 ('1002','20004','1','3'),
 ('1002','20005','1','3'),
 ('1002','20006','1','3'),

 ('1003','20001','1','4'),
 ('1003','20002','1','4'),
 ('1003','20003','2','4'),
 ('1003','20004','1','4'),
 ('1003','20005','1','4');

我做了以下查询:

SELECT * FROM debtor
JOIN items on debtor.debtor = items.debtor AND items.item != '20004'

但我仍然获得了不是'20004'的所有发票行。

如果未显示值'20004',如何以不会执行联接的方式执行查询?

我应该从查询中得到的首选答案应该是只显示 mr Orange

谁能帮帮我?

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT * FROM debtor d
JOIN items i on d.debtor = i.debtor 
WHERE NOT EXISTS 
  (SELECT debtor 
   FROM items i2
   WHERE item = '20004' AND i2.debtor = i.debtor
   )

更新小提琴:http://sqlfiddle.com/#!2/a0826/12/0

答案 1 :(得分:2)

或者这个:

select * from debtor d
join items i on d.debtor = i.debtor 
where d.debtor not in (select debtor from items where item = '20004');

答案 2 :(得分:-1)

如果您只想使用'200004'的发票,则应使用

SELECT * FROM debtor
JOIN items on debtor.debtor = items.debtor AND items.item = '20004'

你用过了!=而不是......可能只是一个错字...

答案 3 :(得分:-1)

您应该将过滤器基于debtor列,因为1001 id是Mister Orange。

SELECT * FROM debtor
JOIN items on debtor.debtor = items.debtor AND debtor.debtor = '1001'

http://sqlfiddle.com/#!2/a0826/19/0