How to join two tables in a database?

The task is this: there is a user table (members) and a unit table (Unit), in the user table there is a column Unit, like in this column to add a unit, for example, with id 1?


Answer 1, authority 100%

Structure:

  • members – id,(some fields),unit_id
  • unit – id,(some fields).

It is possible and necessary to link unit_idand idfrom members. When inserting, first insert into Unit, then substitute idUnitinto members. You can get idUnitas follows. way: through php+mysql, pull it out through the f-th mysql_insert_id, or already when inserting into members, use the mysql function

LAST_INSERT_ID(): INSERT into `members` VALUES (some fields, LAST_INSERT_ID())

This is a general idea, once I did it, read how to use these functions and you will understand everything, if not – write, we will pedal the code. 🙂


Answer 2

Based on the principle of working with databases, the unit field in the members table should store only the unit id. By this id in the units table, you select the unit you need from the database.


Answer 3

If I understood it correctly, something like this:

INSERT INTO table (SELECT * FROM another_table WHERE id="your_id");