Dotazy můžete vyzkoušet na adresehttp://sqlfiddle.com/#!9/839d2/1
Dotaz 1
Seznam všech planet, které mají kapitány. Zobrazuje id_planet, planet_name, celkový počet kapitánů na každé z těchto planet a také počet bitev (pokud vůbec nějaké), které se tam odehrály.
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';
Stejné výsledky můžete získat pomocí tohoto:
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';
Dotaz 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;
Zde jsem nepoužil Joins k výpočtu number_of_soldiers a number_of_battles jako v Query 1.1, protože by to byl korelovaný dílčí dotaz a jako takový by nemohl mít přístup k externím dotazům (https://dev.mysql.com/doc/refman/5.5/en/from-clause -subqueries.html ).
Špatný dotaz:
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';
Výše uvedený dotaz je tedy nesprávný a vytváří chybu:Neznámý sloupec 'aa.id_planet' v klauzuli where.
Pokud jde o druhý dotaz, na který jste se zeptali, doufám, že by to mohl zkusit někdo jiný.