Question

for a practical example, Let's consider trying to model Pokemon elements in SQL.

One element has many strengths and weaknesses, but they themselves are also of type element. How would you model that in a Database?

I believe the solution would be to create an extra 2 tables, perhaps element_strength and element_weakness which would work like joining tables in a many-many relationship. Is this right?

Was it helpful?

Solution

Yes, that would be it, but you can simplify:

Table Element idElement | name

Table Weakness idRow | idElement |idElementStrongAgainst

No need to add a strength table, you just have to look at the weakness table entering by the other column.

So to find the strengths of water you do

SELECT strVS.Name 
FROM Element AS el
JOIN Weakness on el.idElement = Weakness.idElement
JOIN Element As strVS on weakness.idElementStrongAgainst= strVS.idElement
WHERE el.Name = 'water'

and to find the weaknesses:

SELECT weakVS.Name 
FROM Element AS el
JOIN Weakness on el.idElement = Weakness.idElementStrongAgainst
JOIN Element As weakVS on weakness.idElement = weakVS.idElement
WHERE el.Name = 'water'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top