MySQL程序查找给定国家的战舰。内部关系

MySQL程序查找给定国家的战舰。内部关系,mysql,Mysql,我正试图创建一个程序,在这个程序中,给定一个战斗名称,生产出两个在那场战斗中的国家。(如果不存在两个国家,则为这两个国家生成NULL) 程序的第一部分对我来说很重要(我想) 我想这会给我一张表格,列出具体战斗中的不同国家。当我尝试做第二部分时,我的问题就出现了,如果不是两个国家都被发现,那么这两个国家的生产都是空的 CREATE PROCEDURE findCountriesInBattle( in inBattle VARCHAR(50) ) BEGIN SELECT ship FRO

我正试图创建一个程序,在这个程序中,给定一个战斗名称,生产出两个在那场战斗中的国家。(如果不存在两个国家,则为这两个国家生成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;
// 

您应该使用表联接来简化基本查询。通过一个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;
// 

我最讨厌尝试学习这一点的是,我可以完全理解这一点,我只是不能像编写C++/Java那样轻松地输入/流动它。我猜它缺乏语法知识。。。
classes(class, type, country, numGuns, bore, displacement)
ships( name, class, launched)
battles(name, date)
outcomes(ship, battle, result)
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;
//