Question

I am reading Len Silverston data modeling books.

For example, we have two tables:

enter image description here

Len Silverston says:

The primary key to be identified as a combination of the primary key attributes (identified with a "#") as well as the primary keys of the entity to which the relationship with a tilde is pointing.

Therefore the primary key to the ORDER ITEM is the order item seq ID
plus the primary key of the order, order id.

When I implement this model system in RDBMS(Mysql), I am confused that:

  • How to find all Order items which are the children of an Order?

  • When we delete a Order, how to ensure all Order items(children of the Order) was deleted before?

  • What happen if Order item have more than one foreign keys?

Was it helpful?

Solution

"Therefore the primary key to the ORDER ITEM is the order item seq ID plus the primary key of the order, order id."

Looks like an identifying relationship1. Or partial representation of a many-to-many relationship.

In any case, the diagram above is incomplete - it does not show the attribute that was migrated through the relationship. In other words, there should be an "ORDER ID" attribute in "ORDER ITEM" entity.

1 In which case the order of the attributes in the composite key should have been reversed (i.e. {"ORDER ID", "SEQ ID"}), to physically cluster the items of the same order together.


"How to find all Order items which are the children of an Order?"

If you already know ORDER ID, then you can just:

SELECT *
FROM "ORDER ITEM"
WHERE "ORDER ID" = <known value>

Otherwise you can:

SELECT *
FROM "ORDER ITEM"
WHERE "ORDER ID" = (SELECT "ORDER ID" FROM ORDER WHERE <some search criteria>)

Or even:

SELECT "ORDER"."ORDER ID", <other fields...>
FROM "ORDER" JOIN "ORDER ITEM" ON "ORDER"."ORDER ID" = "ORDER ITEM"."ORDER ID"
WHERE <some search criteria>

"When we delete a Order, how to ensure all Order items(children of the Order) was deleted before?"

Probably the easiest way is to use the appropriate cascading referential action...

CREATE TABLE "ORDER ITEM" (
    ...
    FOREIGN KEY ("ORDER ID") REFERENCES ORDER ("ORDER ID") ON DELETE CASCADE
)

...and the DBMS will automatically delete corresponding children when you delete the parent.

Otherwise, you can manually delete like this:

DELETE FROM "ORDER ITEM"
WHERE "ORDER ID" = <known value>

Or even:

DELETE FROM "ORDER ITEM"
WHERE "ORDER ID" = (SELECT "ORDER ID" FROM ORDER WHERE <some search criteria>)

"What happen if Order item have more than one foreign keys?"

Nothing special. The DBMS will enforce referential integrity for each declared foreign key. It is possible to "merge" fields migrated through multiple foreign keys, which is necessary for correctly modeling some situations, and completely wrong for others.

Is there any specific scenario that you'd like to know more about?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top