-1

I have a question. I have 2 tables and I want to inner join from left to right.

The left table contains a foreign key from the right table and it has his own primary key.

Should I join with the primary key + foreign key from the left table since I got the foreign key which has a connection to the right table?

Like for example

ON (left table primary key = left table foreign key)

But I can also use the left and the right table primary keys but what is then the different

ON (left table primary key = right table primary key)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
YuDotNet
  • 1
  • 1
  • Joining **correctly** means linking up the foreign key from one table, with the primary key this FK constraint references in the second table. That's the **whole point** and reason to be for the foreign key constraints! Joining two arbitrary PK doesn't make a whole lot of sense .... – marc_s Nov 09 '21 at 08:01
  • Constraints (including PKs & FKs) need not exist, be known or be declared to record or query. Table meanings are necessary & sufficient. Constraints tell the DBMS about invalid DB states so it can prevent erroneous updates to them. (The comment before this one is misconceived.) [Is there any rule of thumb to construct SQL query from a human-readable description?](https://stackoverflow.com/a/33952141/3404097) PS [CROSS JOIN vs INNER JOIN in SQL](https://stackoverflow.com/a/25957600/3404097) – philipxy Nov 09 '21 at 10:13

1 Answers1

0

In order to locate a row in a SQL table it needs to be uniquely identified by a primary key, this can be a numeric or string value and could use more than one field (a composite primary key).

When this information is used in a related table to reference the original row it is known as a foreign key. You do not need to combine the table's primary key with any foreign key that table holds in order to join the tables.

So you need a join where the left_table.foreign_key = right_table.primary_key

Without some table definitions and names of the actual fields you are using it's hard to give a more specific answer.

Tony
  • 9,672
  • 3
  • 47
  • 75