2014-01-06 62 views
0

這是查詢來獲取用戶合併查詢到1排序

SELECT * FROM users 

然後爲每個用戶,我需要得到信息

SELECT COUNT(user_id) FROM users WHERE refer_id='{$users['user_id']}' 
SELECT COUNT(user_id), SUM(amount) FROM visitors WHERE user_id='{$users['user_id']}' 
SELECT COUNT(user_id) FROM sales WHERE user_id='{$users['user_id']}' 

它們由USER_ID從第一查詢團結。我需要每隔數合併這個查詢訂單

+0

莫非你請發佈幾行預期的輸出結果? – kkuilla

+0

如果你想從多個表中選擇數據,你可以使用JOIN。但的確,發佈一些你想要的輸出數據。 – JeroenJK

回答

0

您可以嵌套子查詢做到這一點:

select u.user_id, count(*) as numusers, 
     (SELECT COUNT(user_id), FROM visitors v WHERE v.user_id = u.user_id) as NumVisitors, 
     (SELECT SUM(amount) FROM visitors v WHERE v.user_id = u.user_id) as VisitorAmount, 
     (SELECT COUNT(user_id) FROM sales s WHERE s.user_id = u.user_id) as NumSales 
from users u 
group by u.user_id; 

您也可以通過加入預先彙總查詢做到這一點:

select u.user_id, v.NumVisitors, v.VisitorAmount, s.NumSales 
from (select u.user_id, count(*) as NumUsers 
     from users u 
     group by u.user_id 
    ) u left outer join 
    (select v.user_id, count(user_id) as NumVisitors, sum(amount) as VisitorAmount 
     from visitors v 
     group by v.user_id 
    ) v 
    on u.user_id = v.visitor_id left outer join 
    (select s.user_id, count(user_id) as NumSales 
     from sales s 
     group by s.user_id 
    ) s 
    on s.user_id = u.user_id;