joeqesi joeqesi - 4 years ago 92
SQL Question

SQL link columns between tables where neither column is UNIQUE

I've started learning SQL to be able to collect data on a production flow as our current method (excel spreadsheet) is outliving it's usefulness.

I'm using SQlite3 to make the database, but I'm running into an issue where I'm trying to create relations between columns of separate tables, but neither column in the relation stores unique values.

For example:

CREATE TABLE process1 (
Product1ID INTEGER PRIMARY KEY,
StartDate TEXT,
EndDate TEXT
);

CREATE TABLE process2 (
Product2ID INTEGER PRIMARY KEY,
StartDate TEXT,
EndDate TEXT
);


As soon as a product has finished process1, it enters process2, so I wanted to constrain any values in process2(StartDate) to be dates already found in process1(EndDate).

But multiple products can start and end process1 (and process2) on the same date, so none of the Date columns in either table contain UNIQUE values, which I understand is a requirement of the Parent Key for Foreign Key constraints.

Is there a way to constrain one column of a table so that all values must already exist in another table's column without either column holding unique values?

Answer Source
CREATE TABLE products(
    ProductID INTEGER PRIMARY KEY,
    ProductName TEXT    
);

CREATE TABLE process1 (
    process1ID INTEGER PRIMARY KEY,
    ProductID integer,
    StartDate TEXT,
    EndDate TEXT,
  CONSTRAINT process1_productid_fkey FOREIGN KEY (productid)
      REFERENCES products (productid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

CREATE TABLE process2 (
    process2ID INTEGER PRIMARY KEY,
    ProductID integer,
    StartDate TEXT,
    EndDate TEXT,
  CONSTRAINT process1_productid_fkey FOREIGN KEY (productid)
      REFERENCES products (productid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

then you can select with a join like this.

 Select * from products p 
 LEFT JOIN process1 p1 on p1.ProductID = p.ProductID
 LEFT JOIN process2 p2 on p2.ProductID = p.ProductID
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download