2016-07-01 71 views
0

所以我有一個DB三表和SQL語法忽略知識結合表記錄

表1;

person_id; 
    person_name; 

表2;

thing_id; 
    thing_name; 

表3;

action_id; 
    action name; 
    thing_id; (referencing thing_id in the table 2) 
    person1_id(referencing person_id in the Table 1); 
    person2_id(referencing person_id in the Table 1); 

基本上,我需要結合顯示第一人稱名稱,第二人稱名稱,動作名稱和事物名稱。我能指導一些正確的加入方式嗎?

+0

http://www.w3schools.com/sql/sql_join.asp – SeanR

+0

謝謝,我仍然不知道如何狀況都人名的顯示。 – 5up9n00b13

回答

1

使用LEFT JOIN

select 
    action_id, 
    action name, 
    a1.thing_name, 
    p1.person_name as person_name1, 
    p2.person_name as person_name2 
from table3 
left join table1 p1 on p1.person_id = table3.person1_id 
left join table1 p2 on p2.person_id = table3.person2_id 
left join table2 a1 on a1.thing_id = table3.thing_id 
+0

它工作得很好。 – 5up9n00b13

1
select t3.action_id, 
     t3.action_name, 
     t1.person_name, 
     t2.person_name 
from table3 t3 
inner join table2 t2 on t2.ting_id = t3.ting_id, 
inner join table1 t1 on t1.person_id = t3.person1_id, 
inner join table1 t2 on t2.person_id = t3.person2_id 
1

在SQL Server中會是這樣的,你可能需要稍微適應爲MySQL。

SELECT p1.person_name AS first_person_name, p2.person_name AS second_person_name, t3.action_name, t2.thing_name 
FROM 
    table3 t3 
    JOIN table1 p1 
     ON p1.person1_id = t3.person_id 
    JOIN table1 p2 
     ON p2.person2_id = t3.person_id 
    JOIN table2 t2 
     ON t2.thing_id = t3.thing_id