Sql 查找只写历史书的作者
SQL新手,但在这个查询中仍然很流行。 这是可行的,尽管Paddy O'Furniture不应该出现,因为这位作者没有写过任何书,他的AUU id也没有出现在title_authors表中。请帮忙 查找只写历史书的作者 select a.au_id, a.au_lname, a.au_fname from authors a where not exists( select ta.au_id from title_authors ta join titles t on t.title_id = ta.title_id where t.type != 'history' and a.au_id = ta.au_id ) 输出: A01布克曼·莎拉Sql 查找只写历史书的作者,sql,Sql,SQL新手,但在这个查询中仍然很流行。 这是可行的,尽管Paddy O'Furniture不应该出现,因为这位作者没有写过任何书,他的AUU id也没有出现在title_authors表中。请帮忙 查找只写历史书的作者 select a.au_id, a.au_lname, a.au_fname from authors a where not exists( select ta.au_id from title_authors ta join titles t
A07 O'Furniture PaddyPaddy O'Furniture出现在结果中,因为在相关子查询中未发现匹配行。i、 e.该作者不存在行,因此“不存在”为真 上述方法在count函数中使用case表达式,因此如果任何书籍具有非历史类型,则该计数将大于零。having子句允许使用聚合值筛选最终结果,having使用在group by子句之后,并且不能替代where子句。您已经接近了。在外部查询中将JOIN添加到title_authors将筛选出尚未写书的作者
select a.au_id, a.au_lname, a.au_fname
from authors a
join title_authors ta1 on ta1.au_id = a.au_id
where not exists(
select 1
from title_authors ta
join titles t on t.title_id = ta.title_id
where t.type != 'history' and ta1.id = ta.id
)
内部查询中的标题作者实际上可以删除
select a.au_id, a.au_lname, a.au_fname
from authors a
join title_authors ta on ta.au_id = a.au_id
where not exists(
select 1
from titles
where t.type != 'history' and title_id = ta.title_id
)
如果您使用另一个exists来确保作者至少写了一本历史书,那么您的方法可以起作用,下面是另一种使用条件聚合的方法:
非常感谢。这个解释帮助我开始。我有很多东西要学。我喜欢这一个,但是我不理解“选择1”-也许我的课程还不足以理解这一点。谢谢你的帮助。
select a.au_id, a.au_lname, a.au_fname
from authors a
join title_authors ta on ta.au_id = a.au_id
where not exists(
select 1
from titles
where t.type != 'history' and title_id = ta.title_id
)
select a.au_id, a.au_lname, a.au_fname
from authors a
join title_authors ta on a.au_id = ta.au_id
join titles t on ta.title_id = t.title_id
group by a.au_id, a.au_lname, a.au_fname
having sum(case when t.type != 'history' then 1 else 0 end) = 0