Mysql
 sql >> Base de données >  >> RDS >> Mysql

Requêtes MySQL de base

Vous pouvez essayer les requêtes sur http://sqlfiddle.com/#!9/839d2/1

Requête 1

Liste de toutes les planètes qui ont des capitaines. Il montre id_planet, planet_name, le nombre total de capitaines sur chacune de ces planètes ainsi que le nombre de batailles (le cas échéant) qui s'y sont déroulées.

SELECT DISTINCT aa.id_planet, aa.planet_name, _aa.captains_count, _bb.battles_count
FROM planet AS aa
INNER JOIN soldier AS bb
ON aa.id_planet = bb.planet_id
INNER JOIN (
    SELECT planet_id, COUNT(*) AS captains_count
    FROM soldier
    WHERE rank = 'captain'
    GROUP BY planet_id
) AS _aa
ON aa.id_planet = _aa.planet_id
LEFT JOIN (
    SELECT id_planet_battle, COUNT(*) AS battles_count
    FROM battle
    GROUP BY id_planet_battle
) AS _bb
ON aa.id_planet = _bb.id_planet_battle
WHERE bb.rank = 'captain';

Vous pouvez avoir les mêmes résultats en utilisant ceci :

SELECT DISTINCT aa.id_planet, aa.planet_name,
(
    SELECT COUNT(*)
    FROM soldier AS _aa
    WHERE _aa.rank = 'captain' AND aa.id_planet = _aa.planet_id
    GROUP BY _aa.planet_id
) AS captains_count,
(
    SELECT COUNT(*)
    FROM battle AS _bb
    WHERE aa.id_planet = _bb.id_planet_battle
    GROUP BY _bb.id_planet_battle 
) AS battles_count
FROM planet AS aa
INNER JOIN soldier AS bb
ON aa.id_planet = bb.planet_id
WHERE bb.rank = 'captain';

Requête 3

SELECT aa.name, aa.rank, bb.planet_name AS planet_from, (
    SELECT COUNT(*) 
    FROM soldier AS _aa 
    WHERE _aa.planet_id = aa.planet_id
) AS number_of_soldiers, 
(
    SELECT COUNT(*)
    FROM battle AS _bb
    WHERE _bb.id_planet_battle = aa.planet_id
) AS number_of_battles
FROM soldier AS aa
INNER JOIN planet AS bb
ON aa.planet_id = bb.id_planet;

Ici, je n'ai pas utilisé Joins pour calculer number_of_soldiers et number_of_battles comme je l'ai fait à la requête 1.1 car ce serait une sous-requête corrélée et en tant que telle, elle ne pourrait pas avoir accès aux requêtes externes (https://dev.mysql.com/doc/refman/5.5/en/from-clause -subqueries.html ).

Requête erronée :

SELECT DISTINCT aa.id_planet, aa.planet_name, _aa.captains_count, _bb.battles_count
FROM planet AS aa
INNER JOIN soldier AS bb
ON aa.id_planet = bb.planet_id
INNER JOIN (
    SELECT COUNT(*) AS captains_count
    FROM soldier AS _aa
    WHERE _aa.rank = 'captain' AND aa.id_planet = _aa.planet_id
    GROUP BY _aa.planet_id
) AS _aa
ON aa.id_planet = _aa.planet_id
LEFT JOIN (
    SELECT COUNT(*) AS battles_count
    FROM battle AS _bb
    WHERE aa.id_planet = _bb.id_planet_battle
    GROUP BY _bb.id_planet_battle 
) AS _bb
ON aa.id_planet = _bb.id_planet_battle
WHERE bb.rank = 'captain';

La requête ci-dessus est donc erronée et produit l'erreur :Colonne inconnue 'aa.id_planet' dans 'clause where'.

En ce qui concerne la deuxième requête que vous avez demandée, j'espère que quelqu'un d'autre pourra l'essayer.