Reputation: 107
I'm trying to get the following behavior:
+-----+--------------+-----+-----+-----+-------+-------+-------+--------+--------+
| id | name | hp | atk | def | spatk | spdef | speed | type1 | type2 |
+-----+--------------+-----+-----+-----+-------+-------+-------+--------+--------+
| 1 | Bulbasaur | 45 | 49 | 49 | 65 | 65 | 45 | GRASS | POISON |
| 2 | Ivysaur | 60 | 62 | 63 | 80 | 80 | 60 | GRASS | POISON |
| 3 | Venusaur | 80 | 82 | 83 | 100 | 100 | 80 | GRASS | POISON |
+-----+--------------+-----+-----+-----+-------+-------+-------+--------+--------+
Where 3 tables are defined as the following:
pokedex:
+----+------------+----+-----+-----+-------+-------+-------+
| id | name | hp | atk | def | spatk | spdef | speed |
+----+------------+----+-----+-----+-------+-------+-------+
| 1 | Bulbasaur | 45 | 49 | 49 | 65 | 65 | 45 |
| 2 | Ivysaur | 60 | 62 | 63 | 80 | 80 | 60 |
| 3 | Venusaur | 80 | 82 | 83 | 100 | 100 | 80 |
+----+------------+----+-----+-----+-------+-------+-------+
poke_type:
+------------+---------+
| pokedex_id | type_id |
+------------+---------+
| 1 | 13 |
| 1 | 5 |
| 2 | 13 |
| 2 | 5 |
+------------+---------+
type:
+----+----------+
| id | name |
+----+----------+
| 1 | NONE |
| 5 | POISON |
| 13 | GRASS |
+----+----------+
It's known that each pokedex
entry associates with 2 type
in the poke_type
table. I attempted to make a query like:
USE pokemon;
SELECT dex.*,
t1.name AS type1,
t2.name AS type2
FROM pokedex AS dex,
(SELECT pt.pokedex_id AS dexid, t.name AS name
FROM pokedex AS d
INNER JOIN poke_type AS pt ON d.id = pt.pokedex_id
INNER JOIN type as t ON pt.type_id = t.id
) AS t1,
(SELECT pt.pokedex_id AS dexid, t.name AS name
FROM pokedex AS d
INNER JOIN poke_type AS pt ON d.id = pt.pokedex_id
INNER JOIN type as t ON pt.type_id = t.id
) AS t2
WHERE dex.id = t1.dexid AND dex.id = t2.dexid AND t1.name <> t2.name
GROUP BY dex.id -- remove duplicates
It's an ugly query and probably not really efficient. Any idea on how to improve this query/select in a different way?
Upvotes: 1
Views: 32
Reputation: 996
If it's not important for you which type is type1 and which type is type2, this is probably the simplest you can get:
SELECT
dex.*,
MAX(t.name) AS type1,
MIN(t.name) AS type2
FROM
pokedex AS dex
JOIN poke_type AS pt ON dex.id = pt.pokedex_id
JOIN type as t ON pt.type_id = t.id
GROUP BY dex.id
Upvotes: 1