我正在尝试创建一个程序,其中给出一个战斗名称,产生两个在该战斗中的国家。 (如果两个国家/地区都没有正好两个国家/地区生成NULL)
程序的第一部分对我来说并不重要(我认为)
SELECT ship FROM outcomes WHERE battle = inBattle AS t1;
SELECT DISTINCT class FROM ships WHERE name IN t1 AS t2;
SELECT DISTINCT country FROM classes WHERE class IN t2;
我想这会给我一张表格,其中列出了具体战斗中不同国家的名单。当我尝试执行第二部分时,我的问题就出现了,如果不是两个国家都发现两个国家都生成NULL。
CREATE PROCEDURE findCountriesInBattle( in inBattle VARCHAR(50) )
BEGIN
SELECT ship FROM outcomes WHERE battle = inBattle AS t1;
SELECT DISTINCT class FROM ships WHERE name IN t1 AS t2;
SELECT DISTINCT country FROM classes WHERE class IN t2 AS t3;
IF(SELECT COUNT(*) FROM t3 < 2 OR SELECT COUNT(*) FROM t3 > 2)
[show NULL, NULL]; << Line 1
ELSE
SELECT * FROM t3; << Line 2
END IF;
END;
//
如何正确编写第1行和第2行?其他行是否正确?
关系:
classes(class, type, country, numGuns, bore, displacement)
ships( name, class, launched)
battles(name, date)
outcomes(ship, battle, result)
答案 0 :(得分:0)
您应该使用表连接来简化基本查询。您可以使用一个SELECT查询将3个表连接在一起,获得给定战斗的不同国家/地区列表。
由于您正在编写存储过程,因此一种直接的方法是首先在局部变量中选择计数,然后使用条件显示国家名称或空值。
以下是基于源代码的示例:
CREATE PROCEDURE findCountriesInBattle( in inBattle VARCHAR(50) )
BEGIN
DECLARE v_country_count INT;
-- count the countries involved in the battle
SELECT COUNT(DISTINCT classes.country)
INTO V_COUNTRY_COUNT
FROM outcomes
INNER JOIN ships ON ships.name = outcomes.ship
INNER JOIN classes ON classes.class = ships.class
WHERE outcomes.battle = inBattle;
IF (v_country_count = 2)
THEN
-- if it was exactly 2, output the names
SELECT DISTINCT classes.country
FROM outcomes
INNER JOIN ships ON ships.name = outcomes.ship
INNER JOIN classes ON classes.class = ships.class
WHERE outcomes.battle = inBattle;
ELSE
-- otherwise, output NULL,NULL
SELECT null
UNION ALL
SELECT null;
END IF;
END;
//