求SQL语句 ,多对多查询
有两张表如下,一张价格表,一张销售订单表,求一语句,查询指定销售订单记录中在销售价格表中不存在的记录(不存在是指不存在物料或存在物料,但价格不等),备注:同一订单上有多条不同物料的记录,价格表中也同一物料也存在多条记录
价格表
物料ID客户ID销售单价
A 100011.2
A 100011.4
A 100011.5
B 2000120
B 2000122
B 2000125
C 。。。。
销售订单表
订单号客户ID物料ID物料数量 物料单价
S0001 10001 A 2000 1.2
S0001 10001 A 1000 1.8
S0001 20001 B 1000 22
S0001 20001 B 3000 25
[解决办法]
- SQL code
select * from 销售订单表 a where not exists(select * from 价格表 where物料ID = a.物料ID and 客户ID = a.客户ID and 销售单价 = a.物料单价)
[解决办法]
- SQL code
select * from 销售订单表 x left outer join 价格表 j on x.物料ID = j.物料IDwhere j.物料id is null or j.销售单价<>x.物料单价
[解决办法]
- SQL code
SELECT *FROM 销售订单表 aWHERE NOT EXISTS (SELECT * FROM 价格表 b WHERE b.物料id = a.物料id AND b.客户id = a.客户id AND b.销售单价 = a.物料单价)
[解决办法]
- SQL code
if object_id('[价格表]') is not null drop table [价格表]gocreate table [价格表]([物料ID] varchar(1),[客户ID] int,[销售单价] numeric(3,1))insert [价格表]select 'A',10001,1.2 union allselect 'A',10001,1.4 union allselect 'A',10001,1.5 union allselect 'B',20001,20 union allselect 'B',20001,22 union allselect 'B',20001,25goif object_id('[销售订单表]') is not null drop table [销售订单表]gocreate table [销售订单表]([订单号] varchar(5),[客户ID] int,[物料ID] varchar(1),[物料数量] int,[物料单价] numeric(3,1))insert [销售订单表]select 'S0001',10001,'A',2000,1.2 union allselect 'S0001',10001,'A',1000,1.8 union allselect 'S0001',20001,'B',1000,22 union allselect 'S0001',20001,'B',3000,25 union allselect 'S0001',20001,'C',2000,25 --为测试增加的记录go-->查询:select * from 销售订单表 twhere not exists(select 1 from 价格表 where 物料ID=t.物料ID and 销售单价=t.物料单价)/**订单号 客户ID 物料ID 物料数量 物料单价----- ----------- ---- ----------- ---------------------------------------S0001 10001 A 1000 1.8S0001 20001 C 2000 25.0(2 行受影响)**/