我想把几个表放到一个脚本中。要做到这一点,我意识到我需要使用INNER JOIN,这让我很困惑。
"SELECT UserSpecies.commonName, UserSpecies.commonNameFR, UserSpecies.commonNameES, UserSpecies.commonNameDE, UserSpecies.speciesName, UserSpecies.speciesRegion, UserSpecies.speciesDetails, UserSpecies.maxSize, UserSpecies.creditSource, UserSpecies.UserCreated, UserSpecies.genusUC, UserSpecies.familyUC, UserSpecies.orderUC, UserSpecies.groupUC, UserSpecies.subGroupUC, UserSpecies.authority, Genus.name, Family.name, Orders.name, Groups.name, SubGroups.name, Types.name, IUCN.name
FROM UserSpecies
INNER JOIN Genus ON UserSpecies.genusKey = Genus.id
INNER JOIN Family ON UserSpecies.familyKey = Family.id
INNER JOIN Orders ON UserSpecies.orderKey = Orders.id
INNER JOIN Groups ON UserSpecies.groupKey = Groups.id
INNER JOIN SubGroups ON UserSpecies.subGroupKey = SubGroups.id
INNER JOIN Types ON UserSpecies.typeKey = Types.id
INNER JOIN IUCN ON UserSpecies.iucnKey = IUCN.id
WHERE UserSpecies.id = %d"
当我运行上述操作时,我没有收到任何错误,但它根本无法检索数据。
注意:所有表格和列都是正确的。
我错过了什么?
答案 0 :(得分:1)
您的数据库中可能缺少信息。
“内连接”语句仅在与连接表有一个(或多个)匹配时才检索数据。
在您的情况下,这意味着如果其中一个联接表中缺少某些数据( Genus ,家庭等等),您将无法获得任何结果。 例如,如果没有系列且ID = UserSpecies.familyKey(在系列表中),您将无法获得数据。
您可以尝试使用“左连接”而不是“内连接”:即使没有匹配也会返回结果。在这种情况下,相应的值将为null:如果没有 Family 匹配,则将为Family.name获取值“null”。通过此修改后的请求,您可以轻松找到丢失的数据(如果有):
"SELECT UserSpecies.commonName, UserSpecies.commonNameFR, UserSpecies.commonNameES, UserSpecies.commonNameDE, UserSpecies.speciesName, UserSpecies.speciesRegion, UserSpecies.speciesDetails, UserSpecies.maxSize, UserSpecies.creditSource, UserSpecies.UserCreated, UserSpecies.genusUC, UserSpecies.familyUC, UserSpecies.orderUC, UserSpecies.groupUC, UserSpecies.subGroupUC, UserSpecies.authority, Genus.name, Family.name, Orders.name, Groups.name, SubGroups.name, Types.name, IUCN.name
FROM UserSpecies
LEFT JOIN Genus ON UserSpecies.genusKey = Genus.id
LEFT JOIN Family ON UserSpecies.familyKey = Family.id
LEFT JOIN Orders ON UserSpecies.orderKey = Orders.id
LEFT JOIN Groups ON UserSpecies.groupKey = Groups.id
LEFT JOIN SubGroups ON UserSpecies.subGroupKey = SubGroups.id
LEFT JOIN Types ON UserSpecies.typeKey = Types.id
LEFT JOIN IUCN ON UserSpecies.iucnKey = IUCN.id
WHERE UserSpecies.id = %d"
如果您想了解“join”关键字的不同风格的更多详细信息,请点击此处: What is the difference between "INNER JOIN" and "OUTER JOIN"?
小心:sqlite仅支持连接操作的子集。