学习内联多表时发现SQL查询错误

时间:2020-03-11 15:13:51

标签: mysql sql inner-join

我正在学习SQL,在做一些练习时,这个问题浮现在我身上。 关于多表查询,我有时看到可以使用Where子句代替内部联接,但是Í尝试使用联接,因为这是我现在要学习的主题。在此示例中,我这样写:

select p.nombre from pokemon p join pokemon_forma_evolucion pfe 
on p.numero_pokedex = pfe.numero_pokedex
join forma_evolucion fo 
on pfe.id_forma_evolucion = fo.id_forma_evolucion
join tipo_evolucion t
on t.tipo_evolucion = fo.tipo_evolucion
where lower(t.tipo_evolucion) = 'intercambio';

但是什么也没显示。 (0个结果)

在“练习”中,博客的正确答案是这个,并且可以很好地显示4个结果:

select p.nombre
from pokemon p, pokemon_forma_evolucion pfe, 
forma_evolucion fe, tipo_evolucion te
where p.numero_pokedex = pfe.numero_pokedex 
and pfe.id_forma_evolucion = fe.id_forma_evolucion
and fe.tipo_evolucion = te.id_tipo_evolucion
and lower(te.tipo_evolucion) = 'intercambio';

我想知道为什么我的无法正常工作以及如何正确使用JOIN命令。 Exercises博客与DER的链接,并访问整个“ pokemon” SQL数据库:https://www.discoduroderoer.es/ejercicios-propuestos-y-resueltos-consultas-sql-bd-pokemon/

感谢您的帮助。我是这个社区的新成员,但这不是我第一次使用和享受它。 谢谢大家

1 个答案:

答案 0 :(得分:1)

where和join应该没问题。问题是您在错误的字段上连接表“ tipo_evolucion”

表FORMA-EVOLUCION中的

fild Tipo_Evolucion是数字的(这是前键)。表TIPO_EVOLUCION中的字段Tipo_Evolucion是varchar2(这不是主键)

TIPO_EVOLUCION的主键是id_tipo_evolucion

因此您的内部联接应为

JOIN tipo_evolucion t ON t.id_tipo_evolucion  = fo.tipo_evolucion

因此查询为:

SELECT p.nombre
FROM pokemon p
     JOIN pokemon_forma_evolucion pfe ON p.numero_pokedex = pfe.numero_pokedex
     JOIN forma_evolucion fo ON pfe.id_forma_evolucion = fo.id_forma_evolucion
     JOIN tipo_evolucion t ON t.id_tipo_evolucion  = fo.tipo_evolucion
WHERE LOWER(t.tipo_evolucion) = 'intercambio';