首页 > 解决方案 > 如果 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

提前为糟糕的英语道歉。

标签: mysqlsqllaravel

解决方案


您需要将条件移至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


推荐阅读