SQL:当有空值时,用字符串替换整数

时间:2017-07-27 08:06:25

标签: mysql sql database database-design

我正在做一些非常类似于这个SO线程(link)的事情。不同之处在于我的桌子有时会有空值。以下是我提供的链接后面的插图。

1)表'人'包含他们最喜欢的运动的人的列表

ID | Name  | FavSport | DislikeSport
------------------------------------
1  | Bob   |    1     |      5
2  | Roy   |    3     |      4
3  | Sarah |          |       
4  | Kevin |    2     |      
5  | Mary  |          |      3

2)表'运动'显示运动列表

ID |   Sport    
---------------
1  | Football   
2  | Basketball  
3  | Volleyball  
4  | Soccer    
5  | Badminton 

我从我在此帖子中发布的链接中获得的查询

select people.Name, sports.Sport 
from people, sports 
where people.FavSport = sports.ID

3)如果查询类似于上面的结果

Name  | Sport      | Dislike
----------------------------
Bob   | Football   | Badminton 
Roy   | Volleyball | Soccer    
Sarah | Football   | Football   
Kevin | Basketball | Football   
Mary  | Football   | Volleyball  

4)我想要的是如下所示的空(或任何默认值,如:没有)

Name  | Sport      | Dislike
----------------------------
Bob   | Football   | Badminton 
Roy   | Volleyball | Soccer    
Sarah |            | 
Kevin | Basketball | 
Mary  |            | Volleyball  

有人如何处理这个问题?提前谢谢。

3 个答案:

答案 0 :(得分:2)

您需要外部联接

select people.Name,
       likes.Sport as FavSport ,
       dislikes.Sport as DislikeSport
from people
left join sports likes
on people.FavSport = likes.ID
left join sports dislikes
on people.DislikeSport = dislikes.ID

JOIN

的标准文档

答案 1 :(得分:1)

SELECT people.NAME, 
       Isnull(sport.sport, '') AS Sport 
FROM   people 
       LEFT JOIN sport 
              ON favsport = sport.id 

答案 2 :(得分:0)

您需要执行left outer join

select people.Name, sports.Sport 
  from people
  left join sports on (people.FavSport = sports.ID);