列出从多个表中获取的相关搜索数据

时间:2013-03-15 02:52:25

标签: sql

尝试将一些表连接在一起以查找某些预订组时遇到一些问题。以下是我创建的表格:

create table Hotel  (
HNo char(4),
Name varchar(20)   not null,
Address varchar(50),
Constraint PK_Hotel Primary Key (HNo))
)


create table Room  (
RNo char(4),
HNo char(4),
Type char(6) not null,
Price decimal (7,2),
Constraint PK_Room Primary Key (HNo, RNo),
Constraint FK_Room Foreign Key (HNo)
references Hotel (HNo)
)


create table Guest  (
GNo char(4),
Name varchar(20) not null,
Address varchar(50),
Constraint PK_Guest Primary Key (GNo)

)


create table Booking   (
HNo char(4),
GNo char(4),
DateFrom date,
DateTo date,
RNo char(4),
Constraint PK_Booking Primary Key (HNo, GNo, DateFrom),
Constraint FK_Booking Foreign Key (GNo)
references Guest (GNo),
Constraint FK_Booking_room Foreign Key (HNo, RNo)
references Room (HNo, RNo),
Constraint FK_Booking_hotel Foreign Key (HNo)
references Hotel (HNo)
)

我需要做的是列出房间号码(RNo),酒店号码(HNo)和所有类型'家庭'的房间类型的价格,按照价格的降序在酒店编号的升序中。

我对如何连接表来执行此操作然后对查询的顺序进行排序有点困惑。任何启蒙都会很感激。

2 个答案:

答案 0 :(得分:1)

这是你要找的吗?

SELECT R.RNo, H.HNo, R.Price
FROM Room R
   INNER JOIN Hotel H ON R.HNo = H.HNo 
WHERE R.Type='family'
ORDER BY R.Price DESC, H.Name ASC

使用INNER JOIN将Room表连接到Hotel表,然后在Room Price DESC上应用ORDER BY,然后在Hotel Name ASC上应用。{/ p>

答案 1 :(得分:0)

SELECT  a.HNO, a.Name,
        b.RNo, b.Type, b.Price
FROM    Hotel a
        INNER JOIN Room b
            ON a.HNo = b.HNo
WHERE   b.Type = 'family'
ORDER   BY b.Price DESC, a.HNo

要进一步了解联接,请访问以下链接: