您可以嵌套子查詢做到這一點:
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;
莫非你請發佈幾行預期的輸出結果? – kkuilla
如果你想從多個表中選擇數據,你可以使用JOIN。但的確,發佈一些你想要的輸出數據。 – JeroenJK