按多个内部联接分组

时间:2018-08-08 17:11:36

标签: mysql

我有一个可以表示为棒球卡交易应用程序的数据集。有两个表可以跟踪一个人拥有和想要的卡片。如果某人拥有一张特定玩家卡牌的多个副本,则owned_cards表中将有多行(此处不包括队伍)。如果有个人要添加的卡片,则在wanted_cards表中插入一行。

owned_cards

| owner | player     |
|-------|------------|
| Fred  | Babe Ruth  |
| Fred  | Babe Ruth  |
| Mary  | Lou Gehrig |
| Mary  | Yogi Berra |
| Mary  | Yogi Berra |

wanted_cards

| owner | player     |
|-------|------------|
| Fred  | Lou Gehrig |
| Fred  | Yogi Berra |
| Mary  | Babe Ruth  |

我正在尝试写一条声明,以“自动匹配”寻求交易的个人。如果一个人拥有一张卡的多个副本,则假定他们将交易其额外物品之一。同样,如果他们仅摆出一张玩家卡的副本,则不会提供该卡进行交易。假定所有卡都具有同等价值。

SELECT fred_wants.player AS 'Fred Wants', mary_has.player AS 'Mary Has'
FROM wanted_cards fred_wants
INNER JOIN owned_cards mary_has ON fred_wants.owner = mary_has.owner
INNER JOIN wanted_cards mary_wants ON mary_has.owner = mary_wants.owner
INNER JOIN owned_cards fred_has ON fred_has.owner = mary_wants.owner
WHERE fred_wants.owner = 'Fred'
GROUP BY mary_has.player
HAVING COUNT(mary_has.player) > 1

产生:

| Fred Wants | Mary Has   |
|------------|------------|
| Lou Gehrig | Babe Ruth  |
| Babe Ruth  | Lou Gehrig |
| Babe Ruth  | Yogi Berra |

所需的输出:

| Fred Wants | Mary Has   |
|------------|------------|
| Babe Ruth  | Yogi Berra |

弗雷德想要一张卢·格里格(Lou Gehrig)卡,但玛丽只有一张,因此不适合交易。摘下GROUP BY,我知道为什么返回行,但是我对如何生成这么多行感到困惑。我以为HAVING会削减它。

1 个答案:

答案 0 :(得分:1)

这是示例查询,该查询返回谁有Fred想要的卡片的额外功能:

select w.player as 'Fred Wants', t.owner as 'Who has extras'
from
wanted_cards as w
inner join
(
  select owner, player
  from owned_cards as o
  where o.owner <> 'Fred'
  group by owner, player
  having count(*) > 1
) as t
on (w.player = t.player)
where w.owner = 'Fred'

主要思想是选择弗雷德想要的所有卡,然后为所有其他玩家找到所有额外的物品