2012-05-23 56 views
1

也許你能幫助我:MYSQL要求

如果有表1:佔

user_id account_id 
39  3799207 
39  80286966 
40  3789458 

...

表2:用戶

id client_id master_id master_account_id active 
1 43   39   3799207    1 
2 43   39   80286966   1 
3 44   39   80286966   1 
4 45   39   80286966   1 

...

使用這個請求:

'SELECT account_id FROM accounts WHERE user_id = "39"'; 

我能得到這個表:

Account 
3799207 
80286966 

我怎樣才能得到這個表:

Account  Subscribers  Count 
3799207  43    1 
80286966  43,44,45...  3 

謝謝!

回答

6

試試這個:

SELECT a.account_id Account, 
     GROUP_CONCAT(b.client_id) Subscribers, 
     COUNT(b.client_id) `Count` 
FROM accounts a INNER JOIN subscribers b 
    on a.account_id = b.master_account_id 
WHERE b.master_id = '39' 
GROUP BY a.account_id 

MySQlSQLite具有內置功能GROUP_CONCAT這concactenates列成行。

HTH

+0

感謝!!!!!!!!!! – user889349