我正在尝试开发SQL代码,以便从我设计的数据库中显示少量信息。我有个问题。查询中的连接是否不正确?请指教。
SELECT o.donutOrder_id, CONCAT(c.FirstName, ',', c.LastName) AS ClientName,
c.HomePhone, d.DonutName, d.DonutDescription, o.order_qty, d.DonutPrice,
o.donut_orderTimestamp
FROM donutOrder AS o
INNER JOIN donut AS d ON d.donut_id = d.donut_id
INNER JOIN customer AS c ON c.customer_id = c.customer_id
以下是表架构:
CREATE TABLE customer (
customer_id INT UNSIGNED NOT NULL,
PRIMARY KEY (customer_id),
LastName VARCHAR (255) NOT NULL,
FirstName VARCHAR (255) NOT NULL,
Street VARCHAR (100) NULL,
Apt VARCHAR (10) NULL,
City VARCHAR (225) NULL,
State CHAR (2) NULL,
Zip CHAR (10) NULL,
HomePhone VARCHAR (20) NULL,
MobilePhone VARCHAR (20) NULL,
OtherPhone VARCHAR (20) NULL
) ENGINE = InnoDB;
CREATE TABLE donut (
donut_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (donut_id) ,
DonutName VARCHAR (50) NOT NULL,
DonutDescription VARCHAR (250) NOT NULL,
DonutPrice DECIMAL (8,2) NOT NULL,
DonutPhotoID VARCHAR (200) NOT NULL
) ENGINE = InnoDB;
CREATE TABLE donutOrder
(
customer_id INT UNSIGNED NOT NULL,
donut_id INT UNSIGNED NOT NULL,
donutOrder_id INT NOT NULL,
donut_orderTimestamp TIMESTAMP DEFAULT NOW(),
order_qty INT NOT NULL,
special_notes VARCHAR(500) NULL,
PRIMARY KEY (donut_id, customer_id),
INDEX (customer_id),
FOREIGN KEY (donut_id) REFERENCES donut (donut_id)
FOREIGN KEY (customer_id) REFERENCES customer (customer_id)
) ENGINE=InnoDB;
答案 0 :(得分:0)
不确定您是否还在寻找答案。您的查询不合逻辑,因为您只是将字段连接到自身。我没有创建表和嵌入的示例数据,所以我无法告诉结果。但是通过将表之间的公共字段等同来加入工作。拿起一本基本的SQL书。
SELECT o.donutOrder_id, CONCAT(c.FirstName, ',', c.LastName) AS ClientName,
c.HomePhone, d.DonutName, d.DonutDescription, o.order_qty, d.DonutPrice,
o.donut_orderTimestamp
FROM donutOrder AS o
INNER JOIN donut AS d ON o.donut_id = d.donut_id
INNER JOIN customer AS c ON o.customer_id = c.customer_id