我有这样的设计
accounts(id, username, email, password, ..)
admin_accounts(account_id, ...)
user_accounts(account_id, ....)
premium_accounts(account_id, ....)
id是帐户中的主键
account_id是外来的(帐户表上的引用ID)和这三个表中的主键(admin,user,premium)
知道id如何才能找到这个用户只有一个查询的类型?还知道id只能存在于三个表之一(admin,user,premium)
答案 0 :(得分:0)
如果您使用UNION
,可以尝试应用此处提出的解决方案 - mysql return table name
答案 1 :(得分:0)
使用case
:
select
a.id,
case
when aa.account_id is not null then 'admin_accounts'
when ua.account_id is not null then 'user_accounts'
when pa.account_id is not null then 'premium_accounts'
else
'No detail found'
end as found_in
from
accounts a
left join admin_accounts aa on aa.account_id = a.id
left join user_accounts ua on ua.account_id = a.id
left join premium_accounts pa on pa.account_id = a.id
/*where -- In case you want to filter.
a.id = ....*/
使用union
select
id,
found_in
from
(select account_id as id, 'admin_accounts' as found_in
from admin_accounts aa
union all
select account_id, 'user_accounts'
from user_accounts ua
union all
select account_id, 'premium_accounts'
from premium_accounts pa) a
/*where -- In case you want to filter.
a.account_id = ....*/
答案 2 :(得分:0)
您可以使用联合查询,例如
(select id, 'admin' as user_type from account inner join admin_accounts) UNION
(select id, 'user' as user_type from account inner join user_accounts) UNION
(select id, 'premium' as user_type from account inner join premium_accounts);