请看下面的图片,我在图片中解释了我的要求。
alt text http://img30.imageshack.us/img30/5668/shippment.png
我无法在WHERE UsageTypeid IN(1,2,3,4)
使用,因为它会表现为OR
条件并获取所有记录。
我只想要第一张桌子的记录,这些记录附有全部4 ShipmentToID
。
结果集中不需要附加3个或更少ShipmentToID
个的所有其他内容。
感谢。
答案 0 :(得分:1)
如果(EntityId, UsageTypeId)
是唯一的:
select s.PrimaryKeyField, s.ShipmentId from shipment s, item a
where s.PrimaryKeyField = a.EntityId and a.UsageTypeId in (1,2,3,4)
group by s.PrimaryKeyField, s.ShipmentId having count(*) = 4
否则,4个字段的4路连接,
select distinct s.* from shipment s, item a, item b, item c, item d where
s.PrimaryKeyField = a.EntityId = b.EntityId = c.EntityId = d.EntityId and
a.UsageTypeId = 1 and b.UsageTypeId = 2 and c.UsageTypeId = 3 and
d.UsageTypeId = 4
你需要(EntityId, UsageTypeId)
上的适当索引,所以它不会挂起......
答案 1 :(得分:0)
这种方式比同一个表方法的多重连接更受欢迎,因为您只需修改IN
子句和COUNT
,而无需在列表中添加或减少更多表到查询ID更改:
select EntityId, ShipmentId
from (
select EntityId
from (
select EntityId
from EntityUsage eu
where UsageTypeId in (1,2,3,4)
group by EntityId, UsageTypeId
) b
group by EntityId
having count(*) = 4
) a
inner join Shipment s on a.EntityId = s.EntityId
答案 2 :(得分:0)
如果第二个表中永远不会有UsageTypeId-EntityId组合的重复项,那么您将永远不会看到:
EntityUsageTypeId | EntityId | UsageTypeId
22685 | 4477 | 1
22687 | 4477 | 1
您可以计算该表中匹配的EntityIds。
WHERE (count(*) in
<tablename
> WHERE EntityId = 4477) = 4
答案 3 :(得分:0)
DECLARE @numShippingMethods int;
SELECT @numShippingMethods = COUNT(*)
FROM shippedToTable;
SELECT tbl1.shipmentID, COUNT(UsageTypeId) as Usages
FROM tbl2 JOIN tbl1 ON tbl2.EntityId = tbl1.EntityId
GROUP BY tbl1.EntityID
HAVING COUNT(UsageTypeId) = @numShippingMethods