【发布时间】: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来决定?
我有一个包含 account_id 和类型的表 A
If type = 1 -> account_id will join with table User
If type = 2 -> account_id wwill join with table Customer
我不知道如何编写 SQL 查询?
请帮忙
【问题讨论】:
在 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;
【讨论】: