Mysql:找到多个孩子的父母

时间:2013-01-27 18:19:25

标签: mysql select one-to-many

我有2张桌子:球员和物品。现在我正在寻找拥有已知属性的项目的球员。

SELECT players.`name` FROM `players`
INNER JOIN `items` ON players.`id`=items.`ownerId` 
WHERE items.`itemType` = 1 AND items.`itemClass` = 2 AND items.`itemColor` = 3

我怎么能找到有多个项目我想要的玩家?甚至可以在一个查询中使用吗?

实施例。我想找到兼具两个项目的玩家:type = 1 class = 2 color = 3,type = 2 class = 3 color = 4

我知道如何在多个查询中执行此操作:只需在每个下一个查询中添加players.id IN(...)。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

执行此操作的最佳方法是使用聚合。

select i.ownerId
from Items i
group by i.ownerId
having max(case when i.itemType = 1 and i.itemClass = 2 and i.itemColor = 3
                then 1 else 0
           end) = 1 and
       max(case when i.itemType = 2 and i.itemClass = 3 and i.itemColor = 4
                then 1 else 0
           end) = 1

如果您需要有关所有者的其他信息,您需要加入玩家表。

在MySQL中,您可以将having子句简化为:

having max(i.itemType = 1 and i.itemClass = 2 and i.itemColor = 3) = 1 and
       max(i.itemType = 2 and i.itemClass = 3 and i.itemColor = 4) = 1