我无法弄清楚我的SQL查询出了什么问题
我的查询
SELECT distinct tp.class, tp.country
FROM classes as tp, (SELECT distinct battle
FROM outcomes
WHERE outcomes.ship in (SELECT ships.name
FROM ships
WHERE ships.class = tp.class)) as sq
GROUP BY tp.class, tp.country;
出现错误
ERROR: invalid reference to FROM-clause entry for table "tp"
LINE 1: ...(select ships.name from ships where ships.class = tp.class))...
^
HINT: There is an entry for table "tp", but it cannot be referenced from this part of the query.
我正在使用PostgreSQL12。
我在堆栈溢出时看到了其他类似的问题,但是我无法从给定的解决方案中找出错误。
答案 0 :(得分:2)
您可以只使用一个简单的join
SELECT distinct tp.class, tp.country
FROM classes as tp join ships on ships.class = tp.class
join outcomes on outcomes.ship=ships.name
答案 1 :(得分:1)
您在from
子句中有一个相关子查询。这是允许的,但是您需要横向连接:
SELECT DISTINCT tp.class, tp.country
FROM classes tp CROSS JOIN LATERAL
(SELECT DISTINCT o.battle
FROM outcomes o
WHERE o.ship IN (SELECT s.name
FROM ships s
WHERE s.class = tp.class
)
) as sq ;
也许还有其他写查询的方法,但这似乎是您在此处尝试的方法。