我对内部查询有疑问
架构:
DEPARTMENT
( deptnum ,descrip,instname,deptname,state,postcode)ACADEMIC
( acnum ,deptnum *,famname,givename,姓名缩写,标题)PAPER
( panum ,标题)AUTHOR
( panum ,acnum **)FIELD
( fieldnum ,id,title)INTEREST
( fieldnum ,acnum **,descrip)我有这种格式的输出:
select
acnum, title, givename, famname
from
academic a
where
a.acnum in (select count(*) as no_of_papers, acnum
from author auth
join paper p on auth.panum = p.panum
group by acnum
having count(*) < 20)
union
select
acnum, title, givename, famname
from
academic a
where
a.acnum not in (select count(*) as no_of_papers, acnum
from author auth
join paper p on auth.panum = p.panum
group by acnum);
但是,除了外部查询的select语句中的字段外,我还希望结果集中的count(*)
为no_of_papers
。
我已经打破了很长一段时间了。
答案 0 :(得分:0)
使用Join
尝试这样
SELECT acnum,title,givename,famname,no_of_papers
FROM academic a JOIN
(
SELECT COUNT(*) AS no_of_papers,acnum
FROM author auth JOIN paper p ON auth.panum=p.panum
GROUP BY acnum HAVING COUNT(*)<20
)x ON 1 = 1
WHERE a.acnum IN (x.acnum)
UNION
SELECT acnum,title,givename,famname,no_of_papers
FROM academic a
(
SELECT COUNT(*) AS no_of_papers,acnum
FROM author auth JOIN paper p ON auth.panum=p.panum
GROUP BY acnum
)y ON 1=1
WHERE a.acnum NOT IN (y.acnum)
答案 1 :(得分:0)
我认为你不需要工会:
select
a.acnum,
MIN(a.title), -- only 1 value anyways if acnum is a primary key
MIN(a.givename),
MIN(a.famname),
count(p.panum) as no_of_papers
from academic a
left join author auth on a.acnum = auth.acnum
left join paper p on auth.panum = p.panum
group by a.acnum
having 1 = 1 -- ??? no_of_papers < 20 ???
;