duanhui9840 2014-09-25 20:10
浏览 85
已采纳

从表中获取NULL值

I want to get null values from other table if it doesn't exist with this query

SELECT * FROM Tithing_P LEFT JOIN Tithing 
ON Tithing_P.Tithing_ID = Tithing.Tithing_ID
WHERE YEAR=2015 AND Dateregistered <=2015

and this only get the opposite of what I wanted.

I have two tables

Tithing
Tithing_ID | Dateregistered | Name |
    1      |   2014-01-01   |   J  |
    2      |   2013-01-01   |   D  |

Tithing.Tithing_ID {PK}
Tithing_P.Tithing_ID {FK} to Tithing.Tithing_ID
Tithing_P_ID {PK}

Tithing_P
Tithing_ID | Tithing_P_ID | Jan | Feb | Year |
     1     |       1      |  10 |  10 | 2014 |

My query is

SELECT * FROM Tithing_P LEFT JOIN Tithing 
ON Tithing_P.Tithing_ID = Tithing.Tithing_ID
WHERE YEAR=2015 AND Dateregistered <=2015

on my page tithing.php?year=2015

I want to show those name who registered earlier from 2015 and if they don't have datas I want Jan and Feb to be 0/NULL

this what I wanted my output to be:
Name |  Jan  |  Feb  |  YEAR  |
  J  |   0   |   0   |  2015  |
  D  |   0   |   0   |  2015  |
  • 写回答

1条回答 默认 最新

  • dongxie9448 2014-09-25 20:16
    关注

    What you are looking for here is an anti-join, which will require you to reverse the order of your tables in the LEFT JOIN, or use a RIGHT JOIN instead, e.g.:

    SELECT * FROM Tithing LEFT JOIN Tithing_P 
    ON Tithing.Tithing_ID = Tithing_P.Tithing_ID
    WHERE Dateregistered <= 2015 AND Tithing_P.Tithing_ID IS NULL
    
    SELECT * FROM Tithing_P RIGHT JOIN Tithing 
    ON Tithing_P.Tithing_ID = Tithing.Tithing_ID
    WHERE Dateregistered <=2015 AND Tithing_P.Tithing_ID IS NULL
    

    The purpose of an anti-join is to discover what records exist on one side of an outer join that do not have any matching records on the other side of the outer join.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件