2017-10-05 95 views
1

我試圖獲得以下行爲:Mysql的提高選擇結表查詢

+-----+--------------+-----+-----+-----+-------+-------+-------+--------+--------+ 
| 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 | 
+-----+--------------+-----+-----+-----+-------+-------+-------+--------+--------+ 

凡3代表的定義如下:

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 | 
+----+----------+ 

據瞭解,每個pokedex項關聯與2 typepoke_type表中。我試圖做一個查詢,如:

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 

這是一個醜陋的查詢,可能不是真的有效。任何想法如何改進這個查詢/選擇以不同的方式?

回答

1

如果不是對你很重要,其類型爲type1和哪種類型是2型,這可能是最簡單的,你可以得到:

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 

sqlfiddle