2014-01-24 72 views
0

存在ID表名我有這樣MySQL來返回

accounts(id, username, email, password, ..) 
admin_accounts(account_id, ...) 
user_accounts(account_id, ....) 
premium_accounts(account_id, ....) 

ID的設計在主鍵佔
ACCOUNT_ID是外國(應收表引用ID)和主鍵這三個表(管理員,用戶,溢價)

知道id我怎麼才能找到哪種類型的用戶只有一個查詢?還知道一個ID只能在三代表一(管理員,用戶,保險費)

回答

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 = ....*/ 
+0

我喜歡這個解決方案,謝謝。 –

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); 
+0

'union all'會更快。 – GolezTrol