我有三个表需要连接在一起。
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/