这是关于战舰及其战斗的模式:
Ships(name, yearLaunched, country, numGuns, gunSize, displacement)
Battles(ship, battleName, result)
典型的Ships元组将是:
('New Jersey', 1943, 'USA', 9, 16, 46000)
这意味着战舰新泽西州于1943年发射;它属于美国,装有9门16英寸(枪管或枪管内径)的枪,加重(以航空方式移位)46,000吨。战斗的典型元组是:
('Hood', 'North Atlantic', 'sunk')
即H.M.S.胡德在北大西洋的战斗中沉没。其他可能的结果是“确定”和“损坏”
问题:列出在战斗中互相争斗的所有国家对。仅列出每对一次,并将其列为首先按字母顺序排在第一位的国家
答案:我写了这个:
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
但是它的名字含糊不清。我该如何解决?提前致谢
答案 0 :(得分:4)
嗯,name = ship
就是问题所在。 name
可以来自a
或b
,ship
来自b1
或b2
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
答案 1 :(得分: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
答案 2 :(得分: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