2016-12-11 68 views
-1

我想選擇STAFF_ID,STAFF_NAMEPROJECT_IDSTAFF_IDPROJECT_ID鏈接在一個表ASSIGNMENTS,但我想要顯示該鏈接,同時也顯示STAFF_NAMESTAFF表中的每個STAFF_ID。這裏是我的代碼:如何從2個表中選擇多個值? SQL Developer

CREATE TABLE PROJECT 
(PROJECT_ID CHAR(5) NOT NULL, 
PROJECT_NAME CHAR(20), 
PROJECT_TYPE CHAR(20), 
START_DATE DATE, 
END_DATE DATE, 
PRIMARY KEY (PROJECT_ID)); 

CREATE TABLE STAFF 
(STAFF_ID CHAR(5) NOT NULL, 
STAFF_NAME CHAR(20), 
JOB_TYPE CHAR(20), 
JOB_GRADE CHAR(20), 
PRIMARY KEY (STAFF_ID)); 

CREATE TABLE ASSIGNMENTS 
(ASSIGNMENT_ID CHAR(5) NOT NULL, 
PROJECT_ID CHAR(5), 
STAFF_ID CHAR(5), 
PRIMARY KEY (ASSIGNMENT_ID), 
FOREIGN KEY (PROJECT_ID) REFERENCES PROJECT(PROJECT_ID), 
FOREIGN KEY (STAFF_ID) REFERENCES STAFF(STAFF_ID)); 

所有表已填入數據,這是到目前爲止,我使用的查詢,顯示該員工在給定的項目工作(但只有STAFF_ID,不與STAFF_NAME包括):

SELECT STAFF_ID, PROJECT_ID 
FROM ASSIGNMENTS 
WHERE PROJECT_ID = 'B0005'; 

如何顯示這樣的鏈接,同時還包括從STAFF表中鏈接到STAFF_ID的STAFF_NAME?

下面是每個表中的行一些數據:

INSERT INTO PROJECT (PROJECT_ID, PROJECT_NAME, PROJECT_TYPE, START_DATE, END_DATE) 
VALUES ('B0001','BIKESHOP.COM','WEB DEVELOPMENT',TO_DATE('15/01/17','DD/MM/YY'),TO_DATE('15/02/17','DD/MM/YY')); 

INSERT INTO STAFF (STAFF_ID, STAFF_NAME, JOB_TYPE, JOB_GRADE) 
VALUES ('ST001','JOHN MASON','WEB DEVELOPER','1'); 

INSERT INTO ASSIGNMENTS (ASSIGNMENT_ID, PROJECT_ID, STAFF_ID, HARDWARE_ID, SOFTWARE_ID) 
VALUES ('A0001','B0001','ST001','H0001','S0001'); 

我想表明的是PROJECT_IDSTAFF_IDSTAFF_NAME。只有三列顯示這3個值。

+0

PLZ給我們一些數據作爲輸入和所希望的輸出。 –

+0

下面是每個表格的一行數據: – JadstaSeven

回答

1

你只需要加入到STAFF表。這樣

SELECT STAFF.STAFF_ID, STAFF.STAFF_NAME, ASSIGNMENTS.PROJECT_ID 
FROM ASSIGNMENTS 
INNER JOIN STAFF ON ASSIGNMENTS.STAFF_ID = STAFF.STAFF_ID 
WHERE ASSIGNMENTS.PROJECT_ID = 'B0005'; 
+0

它很完美,謝謝! – JadstaSeven

+0

歡迎您:) –

0

東西,我覺得這個選擇可以解決你的問題

select PROJECT_ID, STAFF_ID, STAFF_NAME from ASSIGNMENTS 
inner join STAFF on STAFF.STAFF_ID=ASSIGNMENTS.STAFF_ID 
0

爲了實現這一需求,加入了三個表的另一個方法:

通用語法:

select * 
from 
    tableA a 
     inner join 
    tableB b 
     on a.common = b.common 
     inner join 
    TableC c 
     on b.common = c.common 

因此請按照下一個查詢:

select a.PROJECT_ID, b.STAFF_ID, c.STAFF_NAME 
from PROJECT a inner join ASSIGNMENTS b 
on a.PROJECT_ID = b.PROJECT_ID 
inner join STAFF c 
on c.STAFF_ID = b.STAFF_ID 

結果:

enter image description here