组合表记录

时间:2016-07-01 10:15:49

标签: mysql sql

所以我有一个包含三个表的数据库,而且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);

基本上,我需要结合显示第一人名,第二人名,动作名和事名。我可以直接指向一些正确的加入方式吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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