Problems with query JOIN SQL Server

-1

I have two tables

They have Field1 and Field5 in common, so I tried the following query:

Select Campo1, Campo2, Campo3, Campo4, Campo6
From Tabla1 T1 
Inner join Tabla2 T2 
On (T1.Campo1 = T2.Campo5)

hoping to have something like this:

But I do not know why it works for me:

In addition to adding the result, he duplicates it: / Does anybody have an idea? I have already tried with UNION, Left Join and Right Join. Thanks

    
asked by EriK 05.01.2019 в 00:01
source

1 answer

1

Check that in one of the two tables there is no duplicate information. If this is the case, remember to put in the fields "field1" and "field5" as primary keys, putting primary key in the definition of the column when creating the table.

Something of the way.

CREATE TABLE IF NOT EXISTS tabla1 (
  campo1 varchar(250) not null primary key,
  campo2 varchar(250),
  campo3 varchar(250),
  campo4 varchar(250)
);

CREATE TABLE IF NOT EXISTS tabla2 (
  campo5 varchar(250) not null primary key,
  campo6 varchar(250),
  campo7 varchar(250)
);

Or you can delete the duplicates and, only after doing so, create primary keys on those fields.

ALTER TABLE tabla1 ADD PRIMARY KEY (campo1);
ALTER TABLE tabla2 ADD PRIMARY KEY (campo5);

And go back to running the query you have.

O (I do not recommend this), at the end of your query, ask to show it with distinct .

SELECT
  DISTINCT
  campo1,
  campo2,
  campo3,
  campo4,
  campo6
FROM
  tabla1 T1
INNER JOIN
  tabla2 T2
  ON 
    T1.campo1 = T2.campo5
    
answered by 05.01.2019 / 00:30
source