复合结合sql

时间:2010-01-29 10:04:51

标签: sql database hibernate

查询1:这将使用电子邮件'emali@test.com'计算所有记录

select count(*) as total from userbase
join extrauserinfofromhrms on userbase.username = extrauserinfofromhrms.useremail
right join logevent on userbase.username = logevent.useremail
join eachworkflow on logevent.workflowid= eachworkflow.workflowid
where logevent.actionname ='complete'  and logevent.useremail like 'email@test.com'

查询2:使用电子邮件列出所有用户..

select userbase.username from userbase
join extrauserinfofromhrms on userbase.username = extrauserinfofromhrms.useremail

如何使用query2列出所有使用emailaddress的用户,并将每个emailaddrses用作query1中的参数?

1 个答案:

答案 0 :(得分:1)

SQL是一种基于集合的语言。当我们停止逐行思考时,它最有效。您应该使用的是聚合查询:

select userbase.username  
      , count(*) as total 
from userbase 
    join extrauserinfofromhrms on userbase.username = extrauserinfofromhrms.useremail 
    right join logevent on userbase.username = logevent.useremail 
    join eachworkflow on logevent.workflowid= eachworkflow.workflowid 
where logevent.actionname ='complete'  
and logevent.useremail like 'email@test.com' 
group by userbase.username 
/