0

I have the following SQL query

select distinct fnamn,enamn,pubdatum
from author,book
where pubdatum <'1961-0-0 AND author.enamn=book.forfattarenamn;

And this is fine it shows all authors who have a book published before 1961 but what if i want only the authors who published before but not after 1961?

I thought about adding a NOT EXISTS like this

select distinct fnamn,enamn,pubdatum
from author,book
where pubdatum <'1961-0-0' AND author.enamn=book.forfattarenamn
AND NOT EXISTS
(select distinct fnamn,enamn,pubdatum
from author,book
where pubdatum >='1961-0-0' AND author.enamn=book.forfattarenamn);

So in the subquery it list all authors who published after 1961. As i understood it this now removes those authors from the orignal query. but running this SQL statement returns no rows. Have i missunderstood the NOT EXISTS?

mrmagin
  • 61
  • 1
  • 7

2 Answers2

1

You could do sth like this (pls insert into ID the PK of author):

select distinct a.fnamn,a.enamn,b.pubdatum
from author as a
inner join book as b ON a.enamn=b.forfattarenamn
where b.pubdatum <'1961-0-0'
AND NOT EXISTS
(select 0
from author as aX
inner join book as bX on ax.enamn=bx.forfattarenamn
where bx.pubdatum >='1961-0-0' AND aX.ID = a.ID);
Nebi
  • 306
  • 2
  • 10
0

What if i want only the authors who published before but not after 1961?

One simple method uses group by and having:

select a.fnamn, a.enamn, max(b.pubdatum)
from author a inner join
     book b 
     on a.enamn = b.forfattarenamn
group by a.fnamn, a.enamn
having max(b.pubdatum) < '1961-01-01';
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786