Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a LEFT JOIN in MS Access without duplicates?

I have 2 tables with duplicated values in one of the columns. I'd like to do a left join without taking rows, where mentioned column values duplicates. For example, i have table X:

id  Value
A   2
B   4
C   5

and table Y:

id   Value
A  2
A  8
B  2

I'm doing a LEFT JOIN:

SELECT*
FROM X LEFT JOIN Y ON X.id = Y.id;

Would like to have something like:

id   Value
A   2   A   2
B   4   B   2
C   5

so that duplicated id (A 8) from table Y is not considered.

like image 300
Ale Avatar asked Sep 19 '14 16:09

Ale


People also ask

How do you avoid duplicates in join?

How do I prevent duplicate rows from joining multiple tables? Solution. Select column values in a specific order within rows to make rows with duplicate sets of values identical. Then you can use SELECT DISTINCT to remove duplicates.

Can LEFT join cause duplicates?

Again, if we perform a left outer join where date = date, each row from Table 5 will join on to every matching row from Table 4. However, in this case, the join will result in 4 rows of duplicate dates in the joined DataSet (see Table 6).

Why is my join duplicating rows?

In some cases, you need to join tables by multiple columns. In these situations, if you use only one pair of columns, it results in duplicate rows.

How do you remove repeating values in access?

On the Design tab, click Run. Verify that the query returns the records that you want to delete. Click Design View and on the Design tab, click Delete. Access changes the select query to a delete query, hides the Show row in the lower section of the design grid, and adds the Delete row.


2 Answers

You can do it with GROUP BY:

SELECT X.id, X.value, MIN(Y.value)
FROM X
LEFT JOIN Y ON X.id = Y.id
GROUP BY X.id, X.value

Note that it is not necessary to bring Y.id into the mix, because it is either null or equal to X.id.

like image 112
Sergey Kalinichenko Avatar answered Oct 23 '22 10:10

Sergey Kalinichenko


You are looking for GROUP BY to aggregate the Y table records, effectively collapsing them down to one row per id. I have chosen MIN but you could use SUM if they are integers like your example data.

SELECT 
    x.id , x.Value, y.id, min(y.value)
FROM 
    X LEFT JOIN Y ON X.id = Y.id 
GROUP BY 
    x.id, x.value, y.id;

I have given exactly what you asked for. But in my opinion the y.Id is unnecessary in the select and group by list.

like image 30
hollystyles Avatar answered Oct 23 '22 10:10

hollystyles