79827867

Date: 2025-11-23 12:30:32
Score: 1
Natty:
Report link

In order to prevent redundancy, you want to link tables to each other with relations.

CREATE TABLE Ship (
    ShipID INT AUTO_INCREMENT PRIMARY KEY,
    ShipName VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE Company (
    CompanyID INT AUTO_INCREMENT PRIMARY KEY,
    CompanyName VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE ShipOwnership (
    OwnershipID INT AUTO_INCREMENT PRIMARY KEY,
    ShipID INT NOT NULL,
    CompanyID INT NOT NULL,
    StartDate DATE NOT NULL,
    EndDate DATE NULL,         -- remains null untill it has another owner. or the ship is discarded

    FOREIGN KEY (ShipID) REFERENCES Ship(ShipID),
    FOREIGN KEY (CompanyID) REFERENCES Company(CompanyID)
);

Who owned the ship when?

INSERT INTO Ship (ShipName)
VALUES ('RMS Titanic');
INSERT INTO Company (CompanyName)
VALUES ('White Star Line');
INSERT INTO ShipOwnership (ShipID, CompanyID, StartDate, EndDate)
SELECT
    s.ShipID,
    c.CompanyID,
    '1909-03-31' AS StartDate,
    '1912-04-15' AS EndDate
FROM Ship s
JOIN Company c
WHERE s.ShipName = 'RMS Titanic'
  AND c.CompanyName = 'White Star Line';


SELECT c.CompanyName
FROM ShipOwnership o
JOIN Ship s   ON o.ShipID = s.ShipID
JOIN Company c ON o.CompanyID = c.CompanyID
WHERE s.ShipName like '%Titanic%'
  AND '1911-06-01' BETWEEN o.StartDate AND ISNULL(o.EndDate, '9999-12-31');
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: joost jasper