我需要提出几个问题,当我尝试:
时,我遇到了麻烦显示具有船长等级和每个星球上战斗次数的士兵的所有行星列表。
ID_PLANET | PLANET_NAME | CAPTAINS COUNT | BATTLES COUNT
SELECT id_planet,planet_name,count(rank) 来自星球 INNER JOIN士兵在planet_id = id_planet 等级='船长';
在他们自己星球的战争中仅的所有士兵的名单。
ID_SOLDIER | NAME_SOLDIER
SELECT id_soldier,name 来自士兵 INNER JOIN planet ON planet_id = id_planet INNER JOIN战斗在id_planet = id_planet_battle 在哪里planet_id = id_planet_battle;
包括下一个在内的士兵名单:
* NAME |排名| PLANET_FROM |来自家庭行星的士兵数量| BATTLES *
继续努力。
我的尝试是一场灾难,所以经过两天的努力,我在这里寻求帮助。
答案 0 :(得分:1)
您可以尝试查询 http://sqlfiddle.com/#!9/839d2/1
查询1
所有拥有船长的行星的清单。它显示了每个行星上的id_planet,planet_name,总队长以及发生在那里的战斗数量(如果有的话)。
var textHide = document.querySelectorAll(".hide");
您可以使用此结果获得相同的结果:
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';
查询3
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';
在这里,我没有使用Joins来计算number_of_soldiers和number_of_battles,就像我在查询1.1中所做的那样,因为那将是一个相关的子查询,因此它无法访问外部查询(https://dev.mysql.com/doc/refman/5.5/en/from-clause-subqueries.html)。
查询错误:
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;
因此上述查询错误并产生错误:'where子句'中的未知列'aa.id_planet'。
至于您要求的第二个查询,我希望其他人可以尝试一下。