简体   繁体   中英

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).

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). Now i'm not sure about the link between monsters and treasures aswell. Each treasure has 0 or 1 monster. 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. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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