用于连接三个表的Mysql查询

时间:2012-05-24 16:20:16

标签: mysql

我有三张桌子。

请求 - request_id,request_message,requester_id

  • 请求者
  • requesters_id,requesters_name
  • 应答
  • response_id,request_id,response_message

我想从请求中获取所有字段从请求者中选择requestter_id,其中requestter_id位于请求表中, request_id的响应计数来自回复表。

请帮帮我。

由于

2 个答案:

答案 0 :(得分:0)

我从子选择中获取计数,然后将其他两个表与常规连接一起加入

SELECT r.*, rn.requesters_name, 
    (SELECT COUNT(response_id) 
       FROM responses rp WHERE r.request_id=rp.request_id) 
    AS response_count
FROM requests r JOIN requester rn ON r.requesters_id=rn.requesters_id 

答案 1 :(得分:0)

SELECT requests.*,requesters.requesters_name,count(1) AS c FROM requests
LEFT JOIN requesters ON requesters.requester_id = request.requester_id
LEFT JOIN responses ON responses.request_id = requests.request_id
GROUP BY requests.request_id