此文件顯示客戶數據庫和CD數據庫。
客戶被外鍵爲buyerIDs
。一些客戶/買家已經購買了一張特定CD的多份副本。
我創建在記事本文件++,導入到phpMyAdmin的,我打得四處查詢部分來嘗試獲得的例子聲明:phpMyAdmin - SQL查詢
Customer Gerald Bostick bought 3 copies of Thick as a Brick
我想出了查詢:
SELECT `customer`.`CustName`, `customer`.`CDPurchases`, `cd`.`Title`
FROM `customer`, `cd`
我得到的是表中的每一個購買CD一位客戶:
Joe Doe 12 Ascension
Suzy Creamcheese 3 Ascension
Jane Doe 1 Ascension
Gerald Bostick 3 Ascension
Lisa Simpson NULL Ascension
Joe Doe 12 The Velvet Rope
Suzy Creamcheese 3 The Velvet Rope
Jane Doe 1 The Velvet Rope
Gerald Bostick 3 The Velvet Rope
Lisa Simpson NULL The Velvet Rope
Joe Doe 12 The Pecan Tree
Suzy Creamcheese 3 The Pecan Tree
Jane Doe 1 The Pecan Tree
Gerald Bostick 3 The Pecan Tree
Lisa Simpson NULL The Pecan Tree
是外鍵設置是否正確?我改變了它從
CONSTRAINT FK_Buyer FOREIGN KEY FK_Buyer (BuyerId)
REFERENCES Customer (CustID)
到
CONSTRAINT FK_Buyer FOREIGN KEY (BuyerId)
REFERENCES Customer (CustID)
或者是SET
陳述或我的查詢不正確的?
我的編碼是:
DROP DATABASE IF EXISTS Library;
CREATE DATABASE Library;
USE Library;
DROP TABLE IF EXISTS Customer;
DROP TABLE IF EXISTS CD;
CREATE TABLE Customer (
CustID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
CustName VARCHAR(20) NOT NULL,
CDPurchases INTEGER,
PRIMARY KEY (CustID)
);
CREATE TABLE CD (
CDID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Title VARCHAR(45) NOT NULL,
BuyerId INTEGER UNSIGNED,
Price FLOAT(6,2) UNSIGNED NOT NULL,
PRIMARY KEY (CDID),
CONSTRAINT FK_Buyer FOREIGN KEY (BuyerId)
REFERENCES Customer (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Customer VALUES (null, "Joe Doe", 12);
SET @joedoe := LAST_INSERT_ID();
INSERT INTO Customer VALUES (null, "Suzy Creamcheese", 3);
INSERT INTO Customer VALUES (null, "Jane Doe", 1);
SET @janedoe := LAST_INSERT_ID();
INSERT INTO Customer VALUES (null, "Gerald Bostick",3);
SET @geraldbostick := LAST_INSERT_ID();
INSERT INTO Customer VALUES (null, "Lisa Simpson", null);
INSERT INTO CD VALUES (null, "Thriller", @janedoe, 12.99);
INSERT INTO CD VALUES (null, "Grown and Sexy", null, 16.95);
INSERT INTO CD VALUES (null, "Ascension", null, 14.50);
INSERT INTO CD VALUES (null, "The Velvet Rope", null, 13.85);
INSERT INTO CD VALUES (null, "The Pecan Tree", null, 9.99);
INSERT INTO CD VALUES (null, "Condensate", null, 11.85);
INSERT INTO CD VALUES (null, "The Dana Owens Album", null, 9.95);
INSERT INTO CD VALUES (null, "Dustbowl", @joedoe, 17.95);
INSERT INTO CD VALUES (null, "Thick as a Brick", @geraldbostick, 10.95);
感謝您的任何幫助。
爲什麼要將購買數量與客戶關聯起來?你怎麼能告訴他是否買了3張厚厚的磚作爲對比,而不是2份顫慄和阿森鬆之一?你應該有一張包含CDID和CustID的表格;每一行代表一次購買。這被稱爲[數據庫規範化](http://support.microsoft.com/kb/283878)。 – miken32