-2

我有 2 张桌子

投标客户

|bidkey | customerkey
|  1    | 1
|  1    | 2
|  1    | 3

客户组

| groupkey | customerkey 
|    1     |      1
|    1     |      2
|    1     |      3

我想要得到的是一个看起来像的结果

| bidkey | groupkey
|    1   |      1

我尝试了光标并加入,但似乎无法获得我需要的任何想法或建议

编辑:客户也可以属于一个以上的组

4

2 回答 2

2

我不确定谁对您的样本数据有意义。然而下面是一个简单的例子。

询问:

select distinct b.bidkey, g.gkey
from bidcus b
inner join cusgroup g
on 
b.cuskey = g.cuskey
and g.gkey = 10;

结果:

BIDKEY  GKEY
1       10

参考:SQLFIDDLE

于 2012-11-26T12:55:35.597 回答
1

为了在数据库中建立有效的多对多关系,您需要一个定义该关系的中间表,这样您就不会得到重复或不匹配的值。

由于客户匹配,此 select 语句将所有组的所有投标加入。

Select bidkey, groupkey
From customer_groups
Inner Join bid_customer
Where customer_groups.customerkey = Bid_customer.customerkey

她的例子是多对多关系:

多对多关系

对于您的问题:
您将需要另一个连接数据的表。例如,GroupBids

customer_groups并且bid_customer将有一个一对多的关系GroupBids

然后,您将执行以下选择以获取您的数据。

Select bidkey, groupkey 
From bid_customer 
inner join GroupBids 
   ON bid_customer.primarykey = GroupBids.idBidKey
inner join customer_groups 
   ON customer_groups.primarykey = GroupBids.idCustomerGroupkey

这将确保只返回相关的组和出价

于 2012-11-26T12:52:49.200 回答