CREATE TABLE Warehouses
(
Code INTEGER PRIMARY KEY NOT NULL,
Location TEXT NOT NULL, -- 仓库地址
Capacity INTEGER NOT NULL -- 容纳箱子的数量
);
CREATE TABLE Boxes
(
Code TEXT PRIMARY KEY NOT NULL,
Contents TEXT NOT NULL, -- 内容
Value REAL NOT NULL, -- 价值
Warehouse INTEGER NOT NULL, -- 属于那个仓库
CONSTRAINT fk_Warehouses_Code FOREIGN KEY (Warehouse) REFERENCES Warehouses (Code)
);
INSERT INTO Warehouses
VALUES (1, 'Chicago', 3),
(2, 'Chicago', 4),
(3, 'New York', 7),
(4, 'Los Angeles', 2),
(5, 'San Francisco', 8);
INSERT INTO Boxes
VALUES ('0MN7', 'Rocks', 180, 3),
('4H8P', 'Rocks', 250, 1),
('4RT3', 'Scissors', 190, 4),
('7G3H', 'Rocks', 200, 1),
('8JN6', 'Papers', 75, 1),
('8Y6U', 'Papers', 50, 3),
('9J6F', 'Papers', 175, 2),
('LL08', 'Rocks', 140, 4),
('P0H6', 'Scissors', 125, 1),
('P2T6', 'Scissors', 150, 2),
('TU55', 'Papers', 90, 5);
New York
新建一个仓库,可容纳3个箱子H5RT
,包含价值为200
的Papers
,位于仓库2
中select *
from warehouses;
SELECT *
FROM Boxes
WHERE Value > 150;
SELECT DISTINCT Contents
FROM Boxes;
SELECT AVG(Value)
FROM Boxes;
SELECT Warehouse, AVG(Value)
FROM Boxes
GROUP BY Warehouse;
SELECT Warehouse, AVG(Value)
FROM Boxes
GROUP BY Warehouse
HAVING AVG(Value) > 150;
SELECT Boxes.Code, Location
FROM Warehouses
INNER JOIN Boxes
ON Warehouses.Code = Boxes.Warehouse;
/* Not taking into account empty warehouses */
SELECT Warehouse, COUNT(*)
FROM Boxes
GROUP BY Warehouse;
/* Taking into account empty warehouses */
SELECT Warehouses.Code, COUNT(Boxes.Code)
FROM Warehouses
LEFT JOIN Boxes
ON Warehouses.Code = Boxes.Warehouse
GROUP BY Warehouses.Code;
SELECT Code
FROM Warehouses
WHERE Capacity <
(
SELECT COUNT(*)
FROM Boxes
WHERE Warehouse = Warehouses.Code
);
/* Alternate method not involving nested statements */
SELECT Warehouses.Code
FROM Warehouses
JOIN Boxes ON Warehouses.Code = Boxes.Warehouse
GROUP BY Warehouses.Code
HAVING Count(Boxes.Code) > Warehouses.Capacity;
/* Without subqueries */
SELECT Boxes.Code
FROM Warehouses
RIGHT JOIN Boxes
ON Warehouses.Code = Boxes.Warehouse
WHERE Location = 'Chicago';
/* With a subquery */
SELECT Code
FROM Boxes
WHERE Warehouse IN
(
SELECT Code
FROM Warehouses
WHERE Location = 'Chicago'
);
New York
新建一个仓库,可容纳3个箱子INSERT
INTO Warehouses
VALUES (6, 'New York', 3);
H5RT
,包含价值为200
的Papers
,位于仓库2
中INSERT INTO Boxes
VALUES ('H5RT', 'Papers', 200, 2);
UPDATE Boxes
SET Value = Value * 0.85;
UPDATE Boxes
SET Value = Value * 0.80
WHERE Value > (SELECT AVG(Value) FROM (SELECT * FROM Boxes) AS X);
DELETE
FROM Boxes
WHERE Value < 100;
DELETE
FROM Boxes
WHERE Warehouse IN
(
SELECT Code
FROM Warehouses
WHERE Capacity <
(
SELECT COUNT(*)
FROM Boxes
WHERE Warehouse = Warehouses.Code
)
);