如何连接两个表但只返回匹配的行

时间:2016-01-11 22:46:02

标签: sql oracle11g

我有两个表,一个属性表和一个买方表,我试图编写一个选择脚本,该脚本将显示与所需房间数相同的房间数列表顾客。

我认为我需要使用内部联接来提取我需要的数据,但由于我还是新手,我感到有些困惑。我写的选择脚本如下,

SELECT DISTINCT Buyer.Buyer_Surname, Buyer.Rooms_Needed, Property.Property_Address as Property_for_sale, Property.Num_Rooms as Property_No_of_Rooms
FROM Buyer
INNER JOIN Property 
ON Property.Buyer_ID = Buyer.Buyer_ID
WHERE Buyer.Rooms_Needed = '5'
AND Property.Num_Rooms = '5'
AND Buyer.Buyer_ID = '70000';

然而它告诉我没有选择任何行,但我知道有一个买家需要5间卧室和3个属性在数据库中有5间卧室。

这是我的表格;

CREATE TABLE Buyer 
(
Buyer_ID varchar(5) NULL,                           
Viewing_Data varchar2(50),                          
Maximum_Budget varchar2(50),                        
Purchase_Price varchar2(50),                        
Purchase_Date DATE,                                 
Buyer_Forename varchar2(50),                        
Buyer_Surname varchar2(50),                         
Buyer_Address varchar2(50),                         
Buyer_Town varchar2(50),                            
Buyer_Postcode varchar2(10),
Rooms_Needed varchar2(10),
Seller_ID Varchar2(5),
Staff_ID varchar2(5),
PRIMARY KEY (Buyer_ID),
FOREIGN KEY (Staff_ID) REFERENCES Staff(Staff_ID),
FOREIGN KEY (Seller_ID) REFERENCES Seller(Seller_ID)
); 

CREATE TABLE Property 
(
Property_ID varchar(5),                              
Property_Address varchar(25),
Property_Town varchar(25),
Property_Postcode varchar(25),                       
Asking_Price varchar2(20),                           
Date_Registered DATE,                                
Property_Type varchar2(50),                          
Num_Rooms varchar2(50),                              
Buyer_ID varchar(5),                                 
Seller_ID varchar(5),                                
Branch_ID varchar(5),                                
PRIMARY KEY (Property_ID),                           
FOREIGN KEY (Buyer_ID) REFERENCES Buyer(Buyer_ID),
FOREIGN KEY (Seller_ID) REFERENCES Seller(Seller_ID),
FOREIGN KEY (Branch_ID) REFERENCES Branch(Branch_ID)
);

2 个答案:

答案 0 :(得分:2)

您正在选择买方和房产ID。如果这些排队,你会很幸运,但你的结果仍然不正确。要加入房子所拥有的房间数量与买家想要的房间,您需要加入房间数量:

SELECT DISTINCT Buyer.Buyer_Surname, Buyer.Rooms_Needed, 
    Property.Property_Address as Property_for_sale, Property.Num_Rooms as   
    Property_No_of_Rooms
    FROM Buyer
    INNER JOIN Property 
    ON Buyer.Rooms_Needed = Property.Num_Rooms;

如果您需要按房间数量进行过滤,您还可以在最后附加一个WHERE:

... WHERE Buyer.Rooms_Needed = 5;

答案 1 :(得分:1)

尝试此操作,然后加入Buyer.Id和Property.BuyerId

SELECT DISTINCT Buyer.Buyer_Surname, Buyer.Rooms_Needed, Property.Property_Address as Property_for_sale, Property.Num_Rooms as Property_No_of_Rooms
FROM Buyer
INNER JOIN Property 
ON Property.Rooms_Needed = Property.Num_Rooms 
WHERE Buyer.Buyer_ID = '70000';

这将按用户ID 70000找到所需房间数量的所有房产。