Sql Join查询-如果不在连接查询中,则设置默认值

时间:2018-07-27 11:18:53

标签: mysql sql join

我有一个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中的所有马匹。

1 个答案:

答案 0 :(得分:5)

我认为您需要left joincoalesce()

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中没有空格。修复数据效率更高,并且可以防止以后的查询出现问题。