duan33360 2014-02-18 16:27
浏览 104
已采纳

当一个可以为空时,SQL JOIN在两个字段上

I need a little advice on how to create an SQL statement for a particular case in my data. I have two tables with the following fields:

horse_shows table

   horse_shows.showID
   horse_shows.horse_show_date
   horse_shows.horse_show_managerID
   horse_shows.horse_show_secretaryID - this field is allowed to be empty

show_managers table

   show_managers.managerID
   show_managers.name
   show_managers.email

Both horse_show_managerID and horse_show_secretaryID fields in the horse_shows table map to a managerID in the show_managers table. Not all of the shows will have a show secretary, so the horse_show_secretaryID field in the horse_shows table can be blank.

I would like to print the show date, show manager, and show secretary for a show with a specific ID. And if the horse_show_secretaryID field in the horse_shows table is blank, I want it to just print blank for the secretary. So I tried this:

SELECT 
   horse_shows.horse_show_date, 
   show_managers.name, 
   show_secretaries.name 
FROM horse_shows 
   JOIN show_managers ON horse_shows.horse_show_managerID = show_managers.managerID 
   JOIN show_managers as show_secretaries ON horse_shows.horse_show_secretaryID = show_secretaries.managerID 
WHERE horse_shows.showID = 'XYZ';

But, the above statement only returns the row of the show with that showID if it finds a match on both the horse_show_managerID and the horse_show_secretaryID in the show_managers table. If the horse_show_secretaryID field in the horse_shows table is blank (which is a valid condition), the statement returns no rows. I would like it to return the date, manager and (a blank) secretary for the 'XYZ' show when the horse_show_secretaryID field is blank.

Can anyone help me?

Thanks!

  • 写回答

1条回答 默认 最新

  • doushouhe7072 2014-02-18 16:31
    关注

    Using JOIN on it's own will use an INNER JOIN meaning the join condition must be met. Use LEFT JOIN instead:

    SELECT 
       horse_shows.horse_show_date, 
       show_managers.name, 
       show_secretaries.name 
    FROM horse_shows 
       LEFT JOIN show_managers ON horse_shows.horse_show_managerID = show_managers.managerID 
       LEFT JOIN show_managers as show_secretaries ON horse_shows.horse_show_secretaryID = show_secretaries.managerID 
    WHERE horse_shows.showID = 'XYZ';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考