2

以下是关于战舰及其参与的战斗的示意图:

 Ships(name, yearLaunched, country, numGuns, gunSize, displacement)
 Battles(ship, battleName, result)

一个典型的 Ships 元组是:

 ('New Jersey', 1943, 'USA', 9, 16, 46000)

这意味着新泽西号战列舰于1943年下水;它属于美国,携带 9 门 16 英寸(口径或枪管内径)的火炮,重 46,000 吨。Battles 的典型元组是:

 ('Hood', 'North Atlantic', 'sunk')

也就是说,HMS Hood 在北大西洋海战中沉没。其他可能的结果是“正常”和“损坏”

问题:列出所有在战斗中相互交战的国家对。每对只列出一次,并以字母顺序排在第一位的国家列出

答:我写了这个:

SELECT 
    a.country, b.country 
FROM 
    ships a, ships b, battles b1, battles b2 
WHERE 
    name = ship 
    and b1.battleName = b2.battleName 
    and a.country > b.country

但它说的列名不明确。我该如何解决?提前致谢

4

3 回答 3

4

嗯,name = ship是问题。name可能来自aor b,并且ship来自b1orb2

你可以做这样的事情:

select distinct s1.country, s2.country
from ships s1
inner join Battles b1 on b.ship = s1.name
inner join Battles b2 on b2.ship <> s1.name and b2.battleName = b1.battleName
inner join ships s2 on s2.name = b2.ship and s2.country < s1.country
于 2013-10-03T22:40:17.263 回答
1

您可以尝试使用嵌套查询获取赢家和输家的表格,然后将它们加入战斗名称吗?

SELECT
WINNER.country as Country1
,LOSER.country as Country2

FROM
(
  SELECT DISTINCT country, battleName
  FROM Battles 
  INNER JOIN Ships ON Battles.ship = Ships.name
  WHERE Battles.Result = 1
) AS WINNER

INNER JOIN 
(
  SELECT DISTINCT country, battleName
  FROM Battles 
  INNER JOIN Ships ON Battles.ship = Ships.name
  WHERE Battles.Result = 0
) AS LOSER

ON WINNER.battlename = LOSER.battlename
ORDER BY WINNER.country
于 2013-10-03T22:43:01.560 回答
0

试试这个,我认为它很简洁:

SELECT DISTINCT s1.country, s2.country
FROM ships s1, ships s2, battles b1, battles b2 -- i just list all tables here but you can use the left join etc.
WHERE s1.name=b1.ship AND s2.name=b2.ship AND b1.battleName=b2.battleName -- for the tables to join each other
AND s1.country < s2.country --key condition
ORDER BY s1.country ASC
于 2021-03-31T06:45:57.867 回答