mysql - 如果 ID 在另一个表中不匹配,则返回 NULL

标签 mysql sql laravel

我有三个表需要连接在一起。

1- 付款 表:

id
member_id
year_id
notes
paid
paid_at
created_at
updated_at

2- yearly_fees 表:

id
year
amount
created_at
updated_at

3-成员表:

id
first_name
last_name

我想做的是显示 xxxx 年付费和未付费的所有成员(member)的列表。

预期示例输出:

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中是否有匹配的行。

关于mysql - 如果 ID 在另一个表中不匹配,则返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146872/

相关文章:

php - 将请求参数传递给 View - Laravel

php - 查询 : return all rows even if the count of the associated rows are 0

MYSQL 截断不正确的 DOUBLE 值 : Upon multiplying

php - MySQL 使用不同的 WHERE 子句进行多次计数并查看结果

php - 如何连接多个表以根据给定条件获取结果?

javascript - 以一定数量的字符隐藏文章的其余部分

php - 使用 Php 我无法回显 HTML 表格

php - 为什么 'Quantity' 值不显示任何值?

php - 优化mysql递归连接查询

mysql - ZF2 + Doctrine Entity - 将查询作为带有日期时间对象的数组返回?