Boa noite, Estou estudando consultas SQL e me deparei com um problema em uma consulta, tenho duas tabelas: Tabela: Produtos +----------------+--------------+--------+ | Codigo | Produto | Valor | +----------------+--------------+--------+ | 01 | Pipoca | 5.00 | | 02 | Refrigerante | 4.50 | | 03 | Chocolate | 6.00 | | 04 | Amendoas | 18.90 | | 05 | Macarrão | 3.69 | +----------------+--------------+--------+Tabela: Pedidos +----------------+--------------+--------+ | Codigo | Produto | Valor | +----------------+--------------+--------+ | 01 | Pipoca | 2.90 | | 02 | Refrigerante | 4.70 | | 03 | Chocolate | 5.80 | | 04 | Amendoas | 17.90 | | 05 | Macarrão | 4.05 | | 06 | Batata | 7.00 | +----------------+--------------+--------+Preciso fazer uma consulta que me retorne a seguinte tabela: +----------------+--------------+------------+ | Codigo | Produto | Diferenca | +----------------+--------------+------------+ | 01 | Pipoca | 2.10 | | 02 | Refrigerante | -0.20 | | 03 | Chocolate | 0.20 | | 04 | Amendoas | 1.00 | | 05 | Macarrão | 0.36 | | 06 | Batata | 7.00 | +----------------+--------------+------------+Alguem por favor pode me ajudar ?
Assumindo que sua estrutura de dados seja algo como: CREATE TABLE tb_janeiro ( id BIGINT NOT NULL, txt TEXT NOT NULL, PRIMARY KEY( id ) ); CREATE TABLE tb_fevereiro ( id BIGINT NOT NULL, txt TEXT NOT NULL, PRIMARY KEY( id ) );Contendo os seguintes registros: -- INSERE REGISTROS EM JANEIRO INSERT INTO tb_janeiro ( id, txt ) VALUES ( 1, 'ALPHA' ); INSERT INTO tb_janeiro ( id, txt ) VALUES ( 2, 'BETA' ); INSERT INTO tb_janeiro ( id, txt ) VALUES ( 3, 'GAMMA' ); INSERT INTO tb_janeiro ( id, txt ) VALUES ( 4, 'DELTA' ); INSERT INTO tb_janeiro ( id, txt ) VALUES ( 5, 'EPISILON' ); -- INSERE REGISTROS EM FEVEREIRO INSERT INTO tb_fevereiro ( id, txt ) VALUES ( 1, 'ALPHA' ); INSERT INTO tb_fevereiro ( id, txt ) VALUES ( 2, 'BETA' ); INSERT INTO tb_fevereiro ( id, txt ) VALUES ( 3, 'GAMMA' ); INSERT INTO tb_fevereiro ( id, txt ) VALUES ( 4, 'SIGMA' ); INSERT INTO tb_fevereiro ( id, txt ) VALUES ( 5, 'OMEGA' );Você pode usar um LEFT JOIN com uma condição na cláusula WHERE testando se o registro não existe na outra tabela, por exemplo: -- RECUPERA REGISTROS CONTIDOS EM JANEIRO QUE NÃO ESTAO CONTIDOS NA EM FEVEREIRO SELECT jan.id, jan.txt FROM tb_janeiro AS jan LEFT JOIN tb_fevereiro AS fev ON ( jan.txt = fev.txt ) WHERE fev.id IS NULL;Saída: | id | txt | |----|----------| | 4 | DELTA | | 5 | EPISILON |A mesma consulta pode ser usada para fazer o inverso: -- RECUPERA REGISTROS CONTIDOS EM FEVEREIRO QUE NÃO ESTAO CONTIDOS NA EM JANEIRO SELECT fev.id, fev.txt FROM tb_fevereiro AS fev LEFT JOIN tb_janeiro AS jan ON ( jan.txt = fev.txt ) WHERE jan.id IS NULL;Saída: | id | txt | |----|-------| | 4 | SIGMA | | 5 | OMEGA |SQLFiddle: http://sqlfiddle.com/#!9/557e04/1
Aqui, veremos como podemos comparar as colunas de duas tabelas diferentes em SQL. Daremos alguns exemplos para ver como podemos fazer isso de maneiras diferentes. Visão geral: Etapa 1: Criando o banco de dados: Sintaxe - create database_name;Exemplo - create STUDENTS_DATAEtapa 2: Usando o banco de dados: Sintaxe - use database_name;Exemplo - use STUDENT_DATAEtapa 3: Criando a tabela: Tabela 1: Sintaxe - create table table_name ( column1 type, column2 type, ... );Exemplo - create table studentData1 ( roll_number int primary key, firstname varchar(100), lastname varchar(100), marks int );Passo 4: Inserindo registros: Inserindo registros na tabela studentData1 como segue. Sintaxe - Inserindo na tabela studentData1 - insert into studentData1 (roll_number, firstname, lastname, marks) values (1, 'albert', 'einstein',356); insert into studentData1 (roll_number, firstname, lastname, marks) values (2, 'isaac', 'newton',412); insert into studentData1 (roll_number, firstname, lastname, marks) values (3, 'marie', 'curie',436); insert into studentData1 (roll_number, firstname, lastname, marks) values (4, 'philip', 'jsam',389); insert into studentData1 (roll_number, firstname, lastname, marks) values (5, 'tom', 'jsam',452); insert into studentData1 (roll_number, firstname, lastname, marks) values (6, 'tucker', 'jose',412); insert into studentData1 (roll_number, firstname, lastname, marks) values (7, 'drawn', 'csate',389);Etapa 5: Criando a tabela2: Passo 6: Inserindo registros: Exemplo-1: Usando a cláusula where para comparar colunas de duas tabelas diferentes. Ele não pode lidar com os valores nulos. Sintaxe: (para selecionar todos os registros com todas as colunas) select * from table1, table where table1.col1 = table2.col2 and table1.col1 > someValue; Sintaxe (alternativa): Consulta - select * from studentData1, studentData2 where studentData1.roll_number = studentData2.id;Saída:
Exemplo-2: Sintaxe - select t1.col1, t1.col2... , t2.col1, t2.col2... , from table1 as t1 left join table2 as t2 on tabe1.col1 = table2.col1;Consulta - select a.roll_number, a.firstname, b.id from studentData1 as a left join studentData2 as b on a.roll_number = b.id;Saída:
Exemplo-3: Nota - Sintaxe - select col1, col2, col3 .... from (select col1, col2, col3 ... from Table1 union all select col1, col2, col3 ... from Table2) cmpr order by ID;Exemplo - select * from (select * from studentData1 where roll_number > 4 union all select * from studentData2 where id < 6) cmpr order by marks;Saída:
|