【问题标题】:Laravel / Sql: How to join different table with conditionLaravel / Sql:如何使用条件连接不同的表
【发布时间】:2018-05-02 06:13:36
【问题描述】:

我有一个包含 account_id 和类型的表 A

If type = 1 -> account_id will join with table User
If type = 2 -> account_id wwill join with table Customer

我不知道如何编写 SQL 查询?

请帮忙

【问题讨论】:

  • 为什么不用PHP来决定?

标签: php sql laravel join


【解决方案1】:

在 SQL 中,您可以使用两个 left joins 编写此代码:

select a.*,
       coalesce(u.name, c.name) as name  -- how you access a field
from a left join
     users u
     on a.account_id = u.user_id and a.type = 1 left join
     customers c
     on a.account_id = c.customer_id and a.type = 2;

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 2022-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2023-01-10
    • 2015-10-26
    • 2021-09-04
    • 1970-01-01
    相关资源
    最近更新 更多