Laravel / Sql:如何使用条件连接不同的表

时间:2017-11-18 16:03:20

标签: php sql laravel join

我有一个表A包含account_id并输入

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

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

请帮忙

1 个答案:

答案 0 :(得分:1)

在SQL中,你可以用两个left join s来写这个:

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;