MySQL加入多个表

时间:2016-05-20 18:11:58

标签: php mysql sql pdo

我有5张桌子:

comments(id, time, comment, sender, sender_type, user, milestone, time)

users(id, first_name)

representatives(id, first_name)

agents(id, first_name)

lawyers(id, first_name)

有5个不同的里程碑,用户,代表,代理商和律师将发表评论。 The receiver is always the user,发件人可以是代理人,律师或代理人。

我想从评论表中获取给定用户(id)和里程碑的结果。

所以对于前。在里程碑2中,我希望从代表和代理商处获得用户1的所有评论。我想显示评论,发件人姓名,时间,收到评论的用户和评论。

这是我的查询,但我没有得到任何结果(0行)

$milestones = array(
   1 => ["representative"],
   2 => ["representative", "agent"],
   3 => ["representative"],
   4 => ["representative"],
   5 => ["representative", "lawyer"]
);

$allowed_types = '"' . implode('", "', $milestones[$milestone]) . '"';

$query = "
 select c.time, c.comment, u.first_name as user, r.first_name as represantive, l.first_name as lawyer, a.first_name as agent
 from comments c
    join users u
        on c.user = u.id
    left join representatives r
        on c.sender = r.id and c.sender_type = 'representative'
    left join lawyers l
       on c.sender = l.id and c.sender_type = 'lawyer'
    left join agents a
       on c.sender = a.id and c.sender_type = 'agent'
    where
        c.user = $user and c.sender_type in ($allowed_types)
 group by c.time
 order by time asc
 ";

2 个答案:

答案 0 :(得分:1)

改为使用左连接:

select c.time, c.comment, u.first_name as user, r.first_name as represantive, l.first_name as lawyer, a.first_name as agent
from comments c
join users u
   on c.user = u.id
LEFT join representatives r
   on c.sender = r.id
LEFT join lawyers l
  on c.sender = l.id
LEFT join agents a
  on c.sender = a.id
where ...

答案 1 :(得分:1)

您想使用left join但使用正确的类型:

Select ...
From users u join
     Comments c left join
     Representatives r
     On c.sender = r.id and c.type = 'representative' left join 
     ...

您需要在每个联接的on子句中包含该类型。