SQL showing records if they only meet different conditions than usual

Asked

Viewed 48 times

2

I have a slightly different situation, tried different conditions but none brought the desired result.

My need is this:

I have a base containing authors of books and their respective works.

I need to create a query that brings only the authors who had the first book published from 1919.

Follow script for table creation:

CREATE TABLE AUTOR (
    ID INT,
    NOME VARCHAR(255),
    PRIMARY KEY (ID)
);

CREATE TABLE LIVROS (
    ID INT,
    ID_AUTOR INT,
    TITULO VARCHAR(255),
    ANO INT,
    PRIMARY KEY (ID),
    FOREIGN KEY (ID_AUTOR) REFERENCES AUTOR (ID)
);

Follows script for inserting the sampling data:

INSERT INTO AUTOR (ID, NOME) VALUES (1, 'MACHADO DE ASSIS');
INSERT INTO AUTOR (ID, NOME) VALUES (2, 'EUCLIDES DA CUNHA');
INSERT INTO AUTOR (ID, NOME) VALUES (3, 'CLARICE LISPECTOR');
INSERT INTO AUTOR (ID, NOME) VALUES (4, 'JOSÉ DE ALENCAR');
INSERT INTO AUTOR (ID, NOME) VALUES (5, 'MONTEIRO LOBATO');
INSERT INTO AUTOR (ID, NOME) VALUES (6, 'CECÍLIA MEIRELES');

INSERT INTO LIVROS (ID, ID_AUTOR, TITULO, ANO) VALUES (1, 5, 'O Saci-Pererê: resultado de um inquérito', 1918);
INSERT INTO LIVROS (ID, ID_AUTOR, TITULO, ANO) VALUES (2, 5, 'O Picapau Amarelo', 1939);
INSERT INTO LIVROS (ID, ID_AUTOR, TITULO, ANO) VALUES (3, 6, 'Espectros', 1919);
INSERT INTO LIVROS (ID, ID_AUTOR, TITULO, ANO) VALUES (4, 3, 'Perto do Coração Selvagem', 1944);

The correct query should bring the following result:

Result

| id(autor) |       nome(autor)      |
|------------------------------------|
|    6      |    CECÍLIA MEIRELES    |  
|    3      |    CLARICE LISPECTOR   |

Monteiro Lobato will not come in the consultation because it has a publication prior to the year 1919.

  • SELECT * FROM table_livros WHERE ano >= 1919 This will already bring you all the books from 1919 up, if you need ONLY they are from 1919 change the condition >= for ==

  • Search by NOT EXISTS

2 answers

2

Using the IN clause:

SELECT * FROM AUTOR WHERE ID IN (SELECT ID_AUTOR FROM LIVROS GROUP BY ID_AUTOR HAVING MIN(ANO) >= 1919);

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.