MySql - 左边连接与相关表的位置

问题描述 投票:1回答:2

我有这个表:

users
id|name
1|luke
2|john
3|paul

verifications
id|user_id|points|deleted_at
1|1|10|null
2|2|20|null
3|3|30|1-1-2017

目标是让所有用户按verify.points排序,但如果验证未被软删除则考虑验证点,否则使用null作为验证点。有了这个查询:

select users.name from users 
    left join verifications on verifications.user_id = users.id
    where verifications.deleted_at is null
    ORDER BY  verifications.id

我得到了这个结果:

luke (10 ponts)
john (20 points)

但我想要

paul (null points because left join)
luke (10 ponts)
john (20 ponts)

不应考虑30个保密验证点,因为验证是软删除的,我们应该按顺序使用null作为验证点。

有任何想法吗 ?

PS:我想要一个没有子查询的解决方案。

mysql sql laravel
2个回答
2
投票

您可以取消where并在连接条件下检查deleted_at

select u.name, v.points from users u
left join verifications v on v.user_id = u.id and v.deleted_at is null
ORDER BY  v.points

1
投票

如果where有一个值,只需删除case条件并使用null表达式来显示deleted_at点。

select u.name,case when v.deleted_at is null then v.points end as points
from users u
left join verifications on v.user_id = u.id
© www.soinside.com 2019 - 2024. All rights reserved.