Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql - join without duplicating the key

Tags:

sql

postgresql

I want to join two tables with several hundred columns, like this:

select * from a, b where a.key = b.key

The problem is that I get a table that has

Key | Key | Row1 | etc...

Without naming all of the columns explicitly ("select a.key, row1, ... from a, b where a.key = b.key"), is there a way I can limit the query so that it only returns one of the keys?

like image 933
canisrufus Avatar asked Mar 30 '12 14:03

canisrufus


People also ask

How do you avoid duplicates in SQL 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.

How do I join two tables without using the keyword?

You can replace the JOIN keyword with a comma in the FROM clause. What do you do next? There's no ON keyword for you to state the joining condition as there would be when using JOIN , e.g., on which two columns you want to join the tables. In this method, you simply use a WHERE clause to do so.

Does join allow duplicates in SQL?

The answer is yes, if there are any. If there are duplicate keys in the tables being joined.

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.


2 Answers

select * from a INNER JOIN b USING (key)

The USING statement causes the key to only show up once in your result.

like image 180
Hiro2k Avatar answered Oct 08 '22 10:10

Hiro2k


Maybe NATURAL JOIN is solution for you:

SELECT * FROM a NATURAL JOIN b;

But if there are more duplicated key names and you want both of such keys in results, then natural join is not good for you.

like image 23
Jarosław Gomułka Avatar answered Oct 08 '22 09:10

Jarosław Gomułka