mysql - 如果 ID 在另一个表中不匹配,则返回 NULL
问题描述
我有三个表需要连接在一起。
1-payments
表:
id
member_id
year_id
notes
paid
paid_at
created_at
updated_at
2-yearly_fees
表:
id
year
amount
created_at
updated_at
3-members
表:
id
first_name
last_name
我要做的是显示在 xxxx 年支付和未支付的所有成员的列表。
预期的示例输出:
id first_name father_name notes paid year amount
1 test name test last_name test note 1 2018 3000
2 test name test last_name test note NULL NULL NULL
3 test name test last_name test note 1 2018 3000
4 test name test last_name NULL NULL NULL NULL
5 test name test last_name NULL NULL NULL NULL
这是我写的查询:
SELECT `members`.`id`, `members`.`first_name`, `members`.`last_name`,
`payments`.`notes`, `payments`.`paid`, `yearly_fees`.`year`,
`yearly_fees`.`amount` FROM `members`
LEFT JOIN payments ON payments.member_id = members.id
LEFT JOIN yearly_fees ON yearly_fees.id = payments.year_id
WHERE payments.year_id = 4
结果:
id first_name father_name notes paid year amount
1 test name test last_name test note 1 2018 3000
2 test name test last_name test note 1 2018 3000
3 test name test last_name test note 1 2018 3000
该WHERE
语句仅输出与payments
表匹配的行,但我想要的是它也输出每个成员,即使其余行的结果为 NULL。如果我删除该WHERE
声明,它会完全按照我想要的方式工作,但它让我多年来都没有,而不是我特别想要的那个。
这是一个示例输出:
id first_name father_name notes paid year amount
1 test name test last_name test note 1 2016 3000
2 test name test last_name test note 1 2015 3000
3 test name test last_name test note 1 2018 3000
4 test name test last_name test note 1 2018 3000
5 test name test last_name test note 1 2018 3000
6 test name test last_name NULL NULL NULL NULL
7 test name test last_name NULL NULL NULL NULL
提前为糟糕的英语道歉。
解决方案
您需要将条件移至ON
子句:
SELECT `m`.`id`, `m`.`first_name`, `m`.`last_name`,
`p`.`notes`, `p`.`paid`, `yf`.`year`, `yf`.`amount`
FROM `members` m JOIN
yearly_fees yf
ON yf.year_id = 4 LEFT JOIN
payments p
ON p.member_id = m.id AND p.year_id = yf.id;
如果首先更有意义JOIN
yearly_fees
,因为该匹配应该始终存在。然后使用LEFT JOIN
查看是否有匹配的行payments
。
推荐阅读
- javascript - Webpack:无法找到 ID 为 main 的模块——(Aurelia App)
- excel - 基于条件的条件格式的色标
- julia - 在 Julia 1.0+ 中,打印小数点后 pi 的前 2,000 位数字
- dynamics-crm - 为新记录和现有记录生成唯一 ID
- css - 在stylus lang css中为数组添加值
- firebase - google firestore auth 存在规则
- php - 定位搜索 Facebook 语言
- java - Lejos EV3“空指针异常”,但我不知道如何修复它
- java - ObservableList.remove(index, index+1) 导致 UnsupportedOperationException 并且仍然从列表中删除
- microsoft-graph-api - 与图表上的 $filter /messages 不一致