Cross-table constraints in SQL?

Status
Not open for further replies.

syncrotic

Ars Scholae Palatinae
780
A contrived example:

Say we have two types of tools: hammers and wrenches. We have a list of work orders, and we want to track what tool was used for the hammering and what was used for the wrenching.

The problem is that wrenches can be used as hammers (not well, but that's beside the point) but hammers can't be used as wrenches.

Here's what the table structure looks like:

Code:
ORDERS
 OrderNumber  WrenchingTool  HammeringTool
               |              |
               |              |
               `--------------`-----> TOOLS
                                       ToolNumber   ToolType

What I need to do is set a constraint such that the WrenchingTool field can only contain ToolNumbers that have a corresponding ToolType of "Wrench." Meanwhile, the HammeringTool field has no such constraints.

Code:
CREATE TABLE orders (
  OrderNumber integer PRIMARY KEY,
  HammeringTool integer,
  WrenchingTool integer,
  FOREIGN KEY (HammeringTool) REFERENCES tools (ToolNumber),
  FOREIGN KEY (WrenchingTool) REFERENCES tools (ToolNumber),
  CONSTRAINT hammers_cant_wrench _______halp_plox__________,
);

I'm stuck. Can this even be done?
 

Prototyped

Ars Legatus Legionis
11,126
You'd need to effectively have a one-column table, say, "wrenches", that listed only wrenching tools (with a foreign key constraint to "tools"), and you'd reference that rather than the "tools" table for the "WrenchingTool" column. (Effectively you'd be faking inheritance.)

But basically I feel that this schema is rigid, not particularly well normalized, and would do well to have constraints such as this one applied in a business logic layer rather than at this level, since you would actually need as many columns in the "orders" table as types of tools, as many tables as types of tools, and if you ever wanted to enumerate the tools or apply common constraints to them you'd be in great danger of inconsistent behavior.
 

ShuggyCoUk

Ars Legatus Legionis
10,388
Subscriptor++
my only suggestion is a tables Orders, HammeringTools, WrenchingTools and Tools.

Orders has FK to Hammering and wrenching (from the relevant columns) and they in turn are nothing but the PK from tools (and FK back to it)

I suggest not attempting to encode via the schema that wrenching implies Hammering, if a tool can do both it goes in both.

It's more of a pain to insert a tool with the relevant capabilities but it can be augmented with new capabilities easily (and if someone comes up with a safety wrench you can't use as a hammer you're sorted.
 

ShuggyCoUk

Ars Legatus Legionis
10,388
Subscriptor++
oh, thinking of Prototyped answer it occurs to me you could go with Orders, OrderToolUses, Tools and ToolCapabilities.

OrderToolUses is:

OrderNumber, ToolNumber, Use

OrderToolUses has FK to Orders, FK to tools and FK to ToolCapabilities which is

ToolNumber, Use

(If you want you can have a Uses tabe but if the use is simple name this may be overkill)

Then you insert into the ToolUses the various legal combinations, and Orders can have arbitrary sets of tools for various uses.

Obvously if you DON'T want to allow arbitrary uses this may not be appropriate (especially if tool use is mandatory) but it is far more flexible.
 

syncrotic

Ars Scholae Palatinae
780
But basically I feel that this schema is rigid, not particularly well normalized, and would do well to have constraints such as this one applied in a business logic layer rather than at this level, since you would actually need as many columns in the "orders" table as types of tools, as many tables as types of tools, and if you ever wanted to enumerate the tools or apply common constraints to them you'd be in great danger of inconsistent behavior.

Suffice it to say that for this particular application, the only two tasks you'll ever have to do are wrenching and hammering, and the only tools you'll ever be able to use are things that can be categorized as either hammering tools or wrenching tools. I just used a generalized example because I didn't want anyone getting bogged down in domain-specific terminology.


You'd need to effectively have a one-column table, say, "wrenches", that listed only wrenching tools (with a foreign key constraint to "tools"), and you'd reference that rather than the "tools" table for the "WrenchingTool" column. (Effectively you'd be faking inheritance.)

How do I make that one-column Wrenches table automatically from a list of both wrenches and hammers? Can that one-column table actually be a view? That would be confusing and weird :)


my only suggestion is a tables Orders, HammeringTools, WrenchingTools and Tools.

Orders has FK to Hammering and wrenching (from the relevant columns) and they in turn are nothing but the PK from tools (and FK back to it)

If I do as you propose, won't that just make Hammering and Wrenching tables with identical contents?
 

Prototyped

Ars Legatus Legionis
11,126
How do I make that one-column Wrenches table automatically from a list of both wrenches and hammers? Can that one-column table actually be a view? That would be confusing and weird :)

It only has the identifiers for the wrenching tools. It would not have identifiers at all for the tools only good for hammering, not wrenching.

It can be a view, e.g.

Code:
create view wrenches
as
    select toolnumber from tools where can_wrench is true
 

Prototyped

Ars Legatus Legionis
11,126
You could have a view . . . but I think most (all?) RDBMSes won't let you create or at least won't enforce a referential constraint to a view column.

OrderToolUses is:

OrderNumber, ToolNumber, Use

OrderToolUses has FK to Orders, FK to tools and FK to ToolCapabilities which is

ToolNumber, Use

[...]

Then you insert into the ToolUses the various legal combinations, and Orders can have arbitrary sets of tools for various uses.

This wouldn't mandate that ToolNumber and Use in OrderToolUses were found in a tuple in ToolCapabilities.

Instead, you'd need a referential constraint on both ToolNumber and Use:

Code:
create table ToolCapabilities (
    ToolNumber integer not null,
    Use integer not null,
    primary key (ToolNumber, Use),
    foreign key (ToolNumber) references tools (ToolNumber));

create table OrderToolUses (
    Order integer not null,
    ToolNumber integer not null,
    Use integer not null,
    primary key (Order, ToolNumber, Use),
    foreign key (Order) references Orders (Order),
    foreign key (ToolNumber, Use) references ToolCapabilities (ToolNumber, Use));

Now all pairs of ToolNumber and Use associated with the order must exist in ToolCapabilities as a tuple, i.e. the tool must have the capability.

As noted, this does not have the ability to require an order to have a wrench and a hammer, just to allow an order to be associated with tools with only their allowed uses specified.
 

syncrotic

Ars Scholae Palatinae
780
I just realized something: if I have only hammers and wrenches and there is really and truly no circumstance under which I could ever have anything else, then I can just cheat...

I just reduce the table of tools to a single-column list...

Code:
ORDERS
 OrderNumber  WrenchingTool  HammeringTool
               |              |
               |              |
               `--------------`-----> TOOLS
                                       ToolName

Then, within the Tools table, I enforce the constraint that all tool names must start with either an H or a W.

Then I just create a constraint that forces WrenchingTools to start with "W".

Code:
CREATE TABLE orders (
  OrderNumber integer PRIMARY KEY,
  HammeringTool integer,
  WrenchingTool integer,
  FOREIGN KEY (HammeringTool) REFERENCES tools (ToolNumber),
  FOREIGN KEY (WrenchingTool) REFERENCES tools (ToolNumber),
  CONSTRAINT hammers_cant_wrench CHECK Mid(WrenchingTool,1,1) = "W"
);

I don't like it, but I guess I'll throw out normalization for the sake of expediency. I still welcome elegant solutions.
 

Prototyped

Ars Legatus Legionis
11,126
A trigger would do what you need, at the cost of performance and additional complexity. It could perform a select [...] for update on your table of tools to figure out whether the tool was appropriate for the job, and raise an exception if it wasn't.

Oracle example (see section "Referential Integrity Using Triggers")

Triggers tend to be procedural code, so will be specific to the RDBMS you are using.
 
Status
Not open for further replies.