我有来自多个表的多个嵌套选择的查询,如下所示:
select c.name,c.created_date,
( select count(id) from user u
where u.company_id=c.id ) as users,
( select count(distinct uls.user_id) from user_login_status uls
where uls.company_id=c.id
and uls.date between '2013-11-18' and '2014-01-10' ) as unique_logins,
( select count(id) from cash_receiving cr
where cr.company_id=c.id
and cr.created_date between '2013-11-18' and '2014-01-10' ) as recognitions,
0 as licences,
( select count(id) from inventory_item i
where i.company_gid=c.id ) as store_items,
( select count(id) from award a
where a.company_gid=c.id ) as awards,
( select uls2.date from user_login_status uls2
where uls2.company_id=c.id
ORDER BY uls2.date DESC LIMIT 1 ) as last_login,
c.id as id,
c.is_live as live
from company c
order by c.name
user_login_status
包含每个用户登录的条目,因此它将包含大量数据,即sql端,就像我在上面使用实体管理器调用查询的java端一样
所以我想知道上面的查询的性能,它是否适用于每个表的海量数据,或者最好做出单独的选择语句,请告知如何使上述查询表现良好,谢谢。
答案 0 :(得分:0)
试试这个:
SELECT c.name,c.created_date, u.users, uls.unique_logins, cr.recognitions,
0 AS licences, i.store_items, s.awards, uls2.last_login,
c.id AS id, c.is_live AS live
FROM company c
LEFT JOIN (SELECT u.company_id, COUNT(u.id) users
FROM user u
GROUP BY u.company_id
) AS u ON u.company_id = c.id
LEFT JOIN (SELECT uls.company_id, COUNT(DISTINCT uls.user_id) unique_logins
FROM user_login_status uls WHERE uls.date BETWEEN '2013-11-18' AND '2014-01-10'
GROUP BY uls.company_id
) AS uls ON uls.company_id=c.id
LEFT JOIN (SELECT cr.company_id, COUNT(cr.id) recognitions FROM cash_receiving cr
WHERE cr.created_date BETWEEN '2013-11-18' AND '2014-01-10'
GROUP BY cr.company_id
) AS cr ON cr.company_id = c.id
LEFT JOIN (SELECT i.company_gid, COUNT(i.id) store_items
FROM inventory_item i
GROUP BY i.company_gid
) AS i ON i.company_gid = c.id
LEFT JOIN (SELECT a.company_gid, COUNT(a.id) awards
FROM award a
GROUP BY a.company_gid
) AS a ON a.company_gid = c.id
LEFT JOIN (SELECT uls2.company_id, MAX(uls2.date) last_login
FROM user_login_status uls2
GROUP BY uls2.company_id
) AS uls2 ON uls2.company_id=c.id
ORDER BY c.name