SQL多对多选择所需的帮助

时间:2012-11-26 12:43:12

标签: sql

我有2张桌子

Bid_customer

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

customer_groups

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

我想要的是一个看起来像

的结果
| bidkey | groupkey
|    1   |      1

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

编辑:客户也可以属于更多的一个群体

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

此select语句将加入所有组的所有出价,因为客户匹配。

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

她是多对多关系的样本:

Many To Many Relationship

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

customer_groupsbid_customerGroupBids有一对多的关系

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

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

这样可以确保只返回相关的组和出价

相关问题