How to copy auto-increment id value from one table to another

auto-incrementdatabase-designPHP

I have a database with two tables, A and B.

Table A contains the title of a book and has an auto-increment column, book_id, that I declared as primary key.

In table B, I want to retain the price of the book having the same book_id value. In this case, the book_id column will be constrained as a foreign key and I dont want to auto-increment it.

How do I do it using PHP?

Best Answer

Your schema doesn't even make sense. You need to have an authoritative bookid somewhere.

CREATE TABLE book (
  bookid  serial PRIMARY KEY
  -- stuff
);

CREATE TABLE book_title (
  bookid  int REFERENCES book,
  title   text
);

CREATE TABLE book_price (
  bookid  int REFERENCES book,
  price   float
);

That said, if everything is 1:1 with book, just put it all on the same table. You don't need a separate table for every column:

CREATE TABLE book (
  bookid  int serial,
  title   text,
  price   numeric(10,8)
);