Pergunta

I'm having some trouble with using subtypes/supertypes in MySQL. I use C# .NET to make an administration system for my local club, and i have some trouble making a nice database.

My database looks as following:

supertype:

========
Product
---------
Prod_id (PK)
Name
Barcode

and the subtype:

=======
Card
--------
Prod_id (FK)
Price

I have 3 subtypes, Cards, Weapons, Ammonution which are basically the same thing(though i store different things in them)

Maybe i'm overcomplicating things, but all i want to do is, when i create a new Card, that an Product is automatically generated (I use a trigger for that), and that the Cards.Prod_id gets set to the newly generated Product.

How do i do this? Is this the right way of using subtypes, or am i doing something completely wrong?

Foi útil?

Solução

You may use trigger. But, there is another, I think better way:

  • Alter Product table - add AUTO_INCREMENT property to the primary key.
  • Insert new product, MySQL will generate new ID
  • Get last inserted ID using last_insert_id MySQL function, and insert new record in child table

MySQL example:

CREATE TABLE Product(
Prod_id INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(40),
Barcode INT
);

CREATE TABLE Card(
Prod_id INT,
Price DECIMAL(8, 2),
FOREIGN KEY (Prod_id) REFERENCES Product(Prod_id)
);

INSERT INTO Product VALUES (NULL, 'phone', 1000);
INSERT INTO Card VALUES(LAST_INSERT_ID(), 10.5);

First INSERT wall add new product with autogenerated ID. The second, will get this new ID and use it for new Card record.

Using AUTO_INCREMENT

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top