2

let say i have two table, User and Language

user (Table Name)
-----------------
user_id (PK)
user_name
mobile
...
....

language (Table Name)
---------------------
lang_code (PK)
lang_name
...
....

The Question is, if i want to add relationship between user and language table(Many to many) which is a right way ?

solution 1

user_language (Table Name)
--------------------------
user_id (FK)
lang_code (FK)


or solution 2

user_language (Table Name)
--------------------------
user_id (PK)
lang_code (PK)


or solution 3

user_language (Table Name)
--------------------------
user_lang_id (PK)
user_id (FK)
lang_code (FK)

i saw many people add primary key on many to many table, but i think that not important and wasting space. so which is right ?

btw i'm using PostgreSQL

Ahmad
  • 4,224
  • 8
  • 29
  • 40
  • 1
    Composite primary key (user_id, lang_code), with both being foreign keys as well. – Esailija Nov 07 '12 at 16:21
  • Consider the full code example of an n:m relationship I posted just yesterday in a [this related answer](http://stackoverflow.com/a/13259085/939860). That's how you normally do it. – Erwin Brandstetter Nov 07 '12 at 18:09

2 Answers2

4

Personally, I would go with solution 4:

user_language
---------------
user_id (FK)
lang_code (FK)

with composite PRIMARY KEY (user_id, lang_code)

I don't think adding the surrogate key (user_lang_id in solution 3) really adds any value to the schema and simply adds another column to have to worry about. The primary key is a good idea though to maintain uniqueness - without it, you could add the same user_id/lang_code combination multiple times.

lc.
  • 113,939
  • 20
  • 158
  • 187
2

Composite primary key on (user_id,lang_code) is a general approach. You may need surrogate PK if you want to have a reference in another table to user_language, or if you store some other attributes in this table. But even in this case you normally have unique constraint on (user_id,lang_code)

a1ex07
  • 36,826
  • 12
  • 90
  • 103