SQL 联结查询

Posted

技术标签:

【中文标题】SQL 联结查询【英文标题】:SQL junction query 【发布时间】:2015-09-26 05:39:28 【问题描述】:

我对 SQL 非常陌生,我正在尝试对我输入的数据进行查询,以查找 Danmurphys 销售的低于 20 美元的葡萄酒瓶。我编写的查询位于底部,但语法不正确,我不确定自己做错了什么。

您能提供给我的任何帮助将不胜感激!


CREATE TABLE Retailer
(RETAIL_ID NVARCHAR(4) NOT NULL,
RETAIL_NAME NVARCHAR(30) NOT NULL,
PRIMARY KEY (RETAIL_ID));

CREATE TABLE Wine
(WINE_ID NVARCHAR(3) NOT NULL,
WINE_NAME NVARCHAR(30) NOT NULL,
WINE_VINT NVARCHAR(4) NOT NULL,
PRIMARY KEY(WINE_ID));

CREATE TABLE Dist
(RETAIL_ID NVARCHAR(4) NOT NULL,
WINE_ID NVARCHAR(3) NOT NULL,
WINE_PRICE DECIMAL(6,2) NOT NULL,
CONSTRAINT PK_Dist PRIMARY KEY
    (
        RETAIL_ID,
        WINE_ID
    ),
    FOREIGN KEY (RETAIL_ID) REFERENCES Retailer (RETAIL_ID),
    FOREIGN KEY (WINE_ID) REFERENCES Wine (WINE_ID));

INSERT INTO Wine VALUES('101','Grange','2010');
INSERT INTO Wine VALUES('102','Grange','2006');
INSERT INTO Wine VALUES('103','Reserve Shiraz','2013');
INSERT INTO Wine VALUES('104','Grey Label Shiraz','2012');
INSERT INTO Wine VALUES('105','Patricia Shiraz','2009');
INSERT INTO Wine VALUES('106','Ten Acres Shiraz','2012');
INSERT INTO Wine VALUES('107','Double Barrel Shiraz','2012');
INSERT INTO Wine VALUES('108','Platinum Label Shiraz','2006');

INSERT INTO Retailer VALUES('1001', 'Dan Murphys');
INSERT INTO Retailer VALUES('1002', 'Woolworths');

INSERT INTO Dist VALUES('1001','101','750');
INSERT INTO Dist VALUES('1001','102','700');
INSERT INTO Dist VALUES('1001','103','10');
INSERT INTO Dist VALUES('1001','104','35');
INSERT INTO Dist VALUES('1001','105','50');
INSERT INTO Dist VALUES('1001','106','25');
INSERT INTO Dist VALUES('1001','107','15');
INSERT INTO Dist VALUES('1001','108','170');
INSERT INTO Dist VALUES('1002','103','9');
INSERT INTO Dist VALUES('1002','104','33');
INSERT INTO Dist VALUES('1002','105','44');

SELECT DISTINCT Wine.WINE_NAME, Wine.WINE_VINT, Dist.WINE_PRICE
FROM Wine
WHERE WINE_PRICE < 20
INNER JOIN Dist ON Wine.WINE_ID = Dist.RETAIL_ID
INNER JOIN Wine on Dist.RETAIL_ID = Retailer.RETAIL_ID
WHERE retailer.RETAIL_NAME = 'danmurphys'

【问题讨论】:

【参考方案1】:

你快到了。在字符串比较期间,它需要与我们在数据库中的内容相匹配。您可以按以下方式编写查询:

SELECT Wine.WINE_NAME, Wine.WINE_VINT, Dist.WINE_PRICE
FROM Wine
INNER JOIN Dist ON (Wine.WINE_ID = Dist.WINE_ID)
INNER JOIN Retailer on (Dist.RETAIL_ID = Retailer.RETAIL_ID)
WHERE Retailer.RETAIL_NAME = 'Dan Murphys' AND WINE_PRICE < 20

【讨论】:

@MichaelHiggon,我的荣幸!

以上是关于SQL 联结查询的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server进阶:Join联结查询

mysql联表查询,使用phpStudy自带的

1 小时 SQL 极速入门

SQL通过联结表从其他表中选择总和作为列

1 小时 SQL 极速入门

MyBatis:学习笔记——关联查询