我有一个SQL查询,如果两个表中都有一匹马,它将链接2个表以提供数据:
SELECT ProformSystem.TheDate as racedate,
ProformSystem.Course as course,
ProformSystem.TheTime as thetime,
ProformSystem.Horse as horse,
ATRSpeedRatings.rank as rank
FROM ATRSpeedRatings
INNER JOIN ProformSystem ON (ATRSpeedRatings.Horse = trim(ProformSystem.Horse)) AND (ATRSpeedRatings.TheDate = ProformSystem.TheDate) order by ProformSystem.TheTime;"
是否有可能,如果ProformSystem.Horse
中的马不在ATRSpeedRatings.Horse
中,那么我只是将rank = 0
设置为默认值,还是需要运行单独的查询?
这样,即使它们在ProformSystem
中没有排名,我也可以显示ATRSpeedRatings
中的所有马匹。
答案 0 :(得分:5)
我认为您需要left join
和coalesce()
:
SELECT ps.TheDate as racedate, ps.Course as course, ps.TheTime as thetime,
ps.Horse as horse, COALESCE(sr.rank, 0) as rank
FROM ProformSystem ps LEFT JOIN
ATRSpeedRatings sr
ON sr.Horse = TRIM(ps.Horse) AND sr.TheDate = ps.TheDate)
ORDER BY ps.TheTime;
请注意,此查询使用表别名。这些使查询更易于编写和阅读。
此外,JOIN
条件sr.Horse = trim(ps.Horse)
非常值得怀疑。您应该修复数据,以便ProformSystem
中没有空格。修复数据效率更高,并且可以防止以后的查询出现问题。