SQL选择使用join

时间:2017-09-30 12:46:42

标签: sql database oracle select join

我有一张叫做ROOM的桌子。

CONSTRAINT ROOM_PK PRIMARY KEY(BUILDINGNO,ROOMNO),
CONSTRAINT ROOM_FK1 FOREIGN KEY(BUILDINGNO) REFERENCES BUILDING(BUILDINGNO));


BUILDINGNO | ROOMNO | ROOMCAPACITY
-----------+--------+-------------
B1         | R1     | 121
B1         | R2     | 253
B2         | R1     | 275
B2         | R2     | 126
B2         | R3     | 124
B3         | R1     | 256    
B3         | R2     | 324
B4         | R1     | 431
B4         | R2     | 345
B4         | R3     | 231

还有一个名为SESSION的表。

CONSTRAINT SESSION_PK PRIMARY KEY(SESSIONID),
CONSTRAINT SESSION_FK1 FOREIGN KEY(BUILDINGNO) REFERENCES 
BUILDING(BUILDINGNO),
CONSTRAINT SESSION_FK2 FOREIGN KEY(BUILDINGNO,ROOMNO) REFERENCES 
ROOM(BUILDINGNO,ROOMNO),
CONSTRAINT SESSION_FK3 FOREIGN KEY(SPEAKERID) REFERENCES SPEAKER(SPEAKERID)); 


SESSIONID | BUILDINGNO | ROOMNO | SPEAKERID
----------+------------+--------+----------
SS01      | B1         | R1     | S1
SS02      | B2         | R1     | S2
SS03      | B1         | R2     | S2
SS04      | B4         | R2     | S4
SS05      | B3         | R2     | S5
SS06      | B3         | R1     | S5
SS07      | B4         | R2     | S3
SS08      | B1         | R2     | S2
SS09      | B2         | R3     | S4
SS10      | B4         | R1     | S3

我想使用JOIN创建一个SELECT语句,该JOIN显示不在BUILDINGNO'B2'中的SESSION(ID,BUILDINGNO和ROOMNO)的详细信息,而ROOMCAPACITY必须具有> 180.结果也是排除重复值。

我试图使用声明:

SELECT DISTINCT CONFERENCESESSION.SESSIONID, CONFERENCESESSION.BUILDINGNO, CONFERENCESESSION.ROOMNO 
FROM CONFERENCESESSION 
INNER JOIN ROOM ON ROOM.ROOMNO=CONFERENCESESSION.ROOMNO 
WHERE CONFERENCESESSION.BUILDINGNO != 'B2' 
AND ROOM.ROOMCAPACITY >= '180';

然而,这是不对的......有人可以告诉我如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

需要使用整个外键

SELECT DISTINCT CONFERENCESESSION.SESSIONID, CONFERENCESESSION.BUILDINGNO, CONFERENCESESSION.ROOMNO 
FROM CONFERENCESESSION 
INNER JOIN ROOM 
  ON ROOM.BUILDINGNO = CONFERENCESESSION.BUILDINGNO
  ON ROOM.ROOMNO     = CONFERENCESESSION.ROOMNO 
 AND CONFERENCESESSION.BUILDINGNO != 'B2' 
 AND ROOM.ROOMCAPACITY >= '180';

答案 1 :(得分:1)

您需要在JOINBUILDINGNO列的ROOMNO表格中ROOMCAPACITY。假设intSELECT DISTINCT CS.SESSIONID, CS.BUILDINGNO, CS.ROOMNO FROM CONFERENCESESSION CS INNER JOIN ROOM R ON R.BUILDINGNO = CS.BUILDINGNO AND R.ROOMNO = CS.ROOMNO WHERE CS.BUILDINGNO != 'B2' AND R.ROOMCAPACITY >= 180;

{{1}}