SQLServer2000数据库,主从表:dbo.master和dbo.item
master的字段(字段id与从表Item的字段id关联)和数据如下:
id f1
1 A
2 B
Item的字段和数据如下:
id1 id qty
1 1 101
2 1 102
3 2 103
4 2 104
如果sql语句写为:
select a.id,a.f1 from master a,item b where a.id=b.id and b.qty>=101 and
b.qty<=102
显示结果如下:
id f1
1 A
1 A
但是我需要显示结果是:
id f1
1 A
如何写sql语句?但最好不要用grup by(比如:select a.id,a.f1 from master a,
item b where a.id=b.id and b.qty>=101 and b.qty<=102 group by a.id,a.f1),
因为显示字段不止两个,可能十几个字段,那么就要group by 十几个字段,就会很慢的,
能否在where后面处理一下语句?
---------------------------------------------------------------
select a.id,a.f1 from master a left join item b on a.id = b.id
where b.qty>=101 and b.qty<=102
---------------------------------------------------------------
select distinct a.id,a.f1 from master a,item b where a.id=b.id and b.qty>=101 and b.qty<=102
---------------------------------------------------------------
select *
from master
where id in
(select id
from item
where qty >=101 and qty <=102)
---------------------------------------------------------------
为什么不使用自然连接呢?在你的表设计中不是有:字段id与从表Item的字段id关联,只要再加上:master.id=item.id1就行了。
使用distinct是不合适的,原理不一样,只是结果在一定情况下是相同而已。
---------------------------------------------------------------
最好是建立一个视图。利用sql自己带的视图工具相当方便