【问题标题】:MySql - left join with where on related tableMySql - 左连接与相关表上的位置
【发布时间】:2017-12-16 15:52:32
【问题描述】:

我有这张桌子:

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

目标是让所有用户按verification.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)

paul验证中的30分不应该考虑,因为验证是软删除的,我们应该使用null作为他的验证分。

有什么想法吗?

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

【问题讨论】:

    标签: mysql sql laravel


    【解决方案1】:

    您可以取消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
    

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        • 2013-01-27
        • 2013-08-25
        • 1970-01-01
        • 1970-01-01
        • 2015-10-28
        相关资源
        最近更新 更多