· 8 years ago · Aug 20, 2018, 03:46 PM
1drop table if exists carrinho_de_compras;
2drop table if exists usuario;
3drop table if exists livro;
4
5create table if not exists livro (
6 id_livro bigint not null,
7 nome varchar(20) not null,
8 preco double not null,
9 constraint pk_ID_Livro primary key(id_livro)
10);
11
12create table if not exists usuario (
13 id_user smallint not null,
14 nome varchar(40) not null,
15 constraint pk_ID_User primary key(id_user)
16);
17
18create table if not exists carrinho_de_compras (
19 id_user smallint not null,
20 id_livro bigint not null,
21 constraint fk_ID_User foreign key(id_user) references usuario(id_user),
22 constraint fk_ID_Livro foreign key(id_livro) references livro(id_livro)
23);
24
25-- Insere os livros
26insert into livro (id_livro, nome, preco) values
27(1, 'Chapeuzinho Vermelho', 4.20),
28(2, 'Os tres Porquinhos', 3.00),
29(3, 'Branca de Neve', 3.50);
30
31-- Criaos usuarios
32insert into usuario (id_user, nome)
33 values (1, 'Joao da Silva'), (2, 'Pedro Pereira');
34
35-- Adiciona no carrinho de compras
36insert into carrinho_de_compras (id_user, id_livro)
37 values (1, 1), (1, 2), (2, 2);
38
39select usuario.nome, sum(livro.preco) from usuario, livro
40 inner join carrinho_de_compras as c on c.id_user = usuario.id_user
41 and c.id_livro = livro.id_livro;