我有一個複雜的SQL查詢,這意味着返回所選擇的汽車給出的所有評論,但是,我只被顯示一個如下所示,而不是所有的他們喜歡截圖二。SQL查詢只返回一個結果/行而不是全部
這是我DDL
:
CREATE TABLE carsType(
carsTypeID INTEGER NOT NULL AUTO_INCREMENT,
carsTypeName VARCHAR(200) NOT NULL,
PRIMARY KEY(carsTypeID)
);
CREATE TABLE carCategoryType(
carCategoryTypeID INTEGER NOT NULL AUTO_INCREMENT,
carCategoryTypeName VARCHAR(200) NOT NULL,
PRIMARY KEY(carCategoryTypeID)
);
CREATE TABLE cars(
carID INTEGER NOT NULL AUTO_INCREMENT,
carsTypeID INTEGER NOT NULL,
carCategoryTypeID INTEGER NOT NULL,
carName VARCHAR(200),
carArea VARCHAR(200),
FOREIGN KEY(carsTypeID) REFERENCES carsType(carsTypeID),
FOREIGN KEY(carCategoryTypeID) REFERENCES carCategoryType(carCategoryTypeID),
PRIMARY KEY(carID)
);
CREATE TABLE carsReview(
carID INTEGER NOT NULL,
carMileage INTEGER NOT NULL,
reviews VARCHAR(200) NOT NULL,
FOREIGN KEY(carID) REFERENCES cars(carID)
);
INSERT INTO carsType VALUES
(NULL, "Hatchback"),
(NULL, "Saloon"),
(NULL, "Sedan");
INSERT INTO carCategoryType VALUES
(NULL, "A"),
(NULL, "B"),
(NULL, "C");
INSERT INTO cars VALUES
(NULL, 1, 1, "Golf", "Germany"),
(NULL, 2, 2, "Ford", "USA"),
(NULL, 2, 2, "Pontiac", "USA");
INSERT INTO carsReview VALUES
(1, 10000, "Good clean car"),
(2, 3000, "Worth it"),
(3, 1000, "Brand spanking new"),
(1, 45000, "She is good"),
(1, 100000, "Gone son"),
(1, 23000, "Looking fine");
這是我的複雜SQL
查詢:
SELECT tbl_cars.carID, tbl_cars.carName, tbl_cars.carArea,
(IFNULL(tbl_carsReview.averageMileage, 0.0)) AS finalaverageMileage , tbl_carsReview.reviews, tbl_carsType.carsTypeName,
tbl_carCategoryType.carCategoryTypeName
FROM cars tbl_cars
INNER JOIN carsType tbl_carsType ON
tbl_cars.carsTypeID = tbl_carsType.carsTypeID
INNER JOIN carCategoryType tbl_carCategoryType ON
tbl_cars.carCategoryTypeID = tbl_carCategoryType.carCategoryTypeID
LEFT JOIN (SELECT carsReview.carID, ROUND(AVG(carsReview.reviews),1) AS averageMileage, carsReview.reviews
FROM carsReview) tbl_carsReview
ON tbl_cars.carID = tbl_carsReview.carID
WHERE tbl_cars.carID = 1
這是我sqlfiddle
:http://sqlfiddle.com/#!9/c9a92c/8
表別名比表名更長...我更喜歡相反的。 – jarlh