简体   繁体   English

MySQL查询和优化数据库

[英]MySQL Query and optimizing database

I have a project i need to make for school. 我有一个上学需要做的项目。 It's a game made in Javafx based on munchkin (board game). 这是一个基于Javafx的基于munchkin的游戏(棋盘游戏)。

We have a hero, this hero will defeat monsters in a room, and each monster defends a treasure (i'm seeing it as the monster's loot like in a mmorpg). 我们有一个英雄,这个英雄将击败房间中的所有怪物,每个怪物都捍卫着一件宝藏(我将其视为怪物的战利品,就像在mmorpg中一样)。 Now i'm not sure about the link between monsters and treasures aswell. 现在我也不确定怪物和宝藏之间的联系。 Each treasure has 0 or 1 monster. 每个宝藏都有0或1个怪物。 Each monster atleast has one treasure, can be multiple aswell. 每个怪物至少都有一个宝藏,也可以是多个。 The teacher said to use an extra table for this (Treasure_has_Monsters) in my case. 老师说在我的情况下为此使用一个额外的表(Treasure_has_Monsters)。 I'm not sure the references are correct though... 我不确定引用是否正确...

My database at the moment: Database Design 目前我的数据库: 数据库设计

Now the problem i'm having is the following. 现在我遇到的问题如下。 I need to get a list from all the treasures a monster has . 我需要从怪物拥有的所有宝藏中获取清单 And i could query the treasure_has_monster table and get all the id's of treasures and then create a query to get all the treasures with the id's. 而且我可以查询宝藏表拥有所有宝藏的ID,然后创建一个查询以获取所有带有宝藏的ID。

Questions: 问题:

  • Is there a way to do this in one query? 有没有办法在一个查询中做到这一点?
  • Is the reference between Treasures and Monsters ok? 珍宝和怪兽之间的引用可以吗?

You can try making a simple query like: 您可以尝试进行以下简单查询:

SELECT t.name
FROM treasure_has_monster thm
INNER JOIN trasures t ON (thm.trasure_id = t.id)
WHERE thm.monster_id = YOUR_MONSTER_ID

According to your schema, you could try: 根据您的架构,您可以尝试:

select t.* from Treasures t
join Treasures_has_Monsters tm on tm.Treasure_id=t.id
where Monster_id=?

where? 哪里? is the monster id you want to list the treasures for. 是您要列出宝藏的怪物ID。

No reason to join both tables together. 没有理由将两个表连接在一起。 You could use a simple inner query. 您可以使用一个简单的内部查询。

SELECT * FROM Treasures
WHERE id IN (SELECT treasure_id from Treasures_has_Monsters
             WHERE monsterid = <MID>);

replace <MID> with the monster id you want to get <MID>替换为要获取的怪物ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM