如果此查询不存在
,我想从其他表中获取空值SELECT * FROM Tithing_P LEFT JOIN Tithing
ON Tithing_P.Tithing_ID = Tithing.Tithing_ID
WHERE YEAR=2015 AND Dateregistered <=2015
这只会与我想要的相反。
我有两张桌子
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 |
我的查询是
SELECT * FROM Tithing_P LEFT JOIN Tithing
ON Tithing_P.Tithing_ID = Tithing.Tithing_ID
WHERE YEAR=2015 AND Dateregistered <=2015
在我的页面tithing.php?year=2015
我想展示从2015年开始注册的那些名字,如果他们没有数据,我希望Jan和Feb为0 / NULL
this what I wanted my output to be:
Name | Jan | Feb | YEAR |
J | 0 | 0 | 2015 |
D | 0 | 0 | 2015 |
答案 0 :(得分:1)
您在这里寻找的是反连接,它要求您在LEFT JOIN中颠倒表格的顺序,或者使用右连接,例如:
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
反连接的目的是发现在外连接的一侧存在哪些记录在外连接的另一侧没有任何匹配记录。