使用三个表的Mysql连接查询

时间:2012-05-13 12:13:43

标签: mysql

我正在使用三张桌子。在第一个表中记录了客户问题。

  customer_id   |   question   | question_id
----------------------------------------------
       58       |   question 4 |      4
       41       |   question 5 |      5
       37       |   question 3 |      3 

在第二个表中记录了与第一个问题相关的评论

    comment   | question_id   |  user
---------------------------------------
    comment 1 |      4        |    41  
    comment 2 |      5        |    58         
    comment 3 |      4        |    41  
    comment 4 |      5        |    58  
    comment 5 |      3        |    23  

在第三个表中找到有关此站点用户的数据

    user      | status
--------------------------------
     58       |      1
     41       |      1
     37       |      0 
     23       |      0 

如何创建一个查询,该查询将作为按question_id排序的最后五个问题的列表以及与每个问题相关的注释总数。这些问题和评论只能由状态为“1”的用户作为第三个表格。

此示例中的结果应如下所示:

  question   | total comments  |   user
-----------------------------------------------
 question 5  |      2          |    41
 question 4  |      2          |    58    

4 个答案:

答案 0 :(得分:1)

我有理由相信这是正确的,虽然我没有这里的数据来验证。

SELECT questions.question, 
       count(comments.question_id) as 'total comments', 
       user.user
FROM user 
  JOIN questions on user.user = questions.customer_id
  LEFT JOIN comments on questions.question_id = comments.question_id
WHERE user.status = 1
GROUP BY comments.question_id,  questions.question, users.user
ORDER BY questions.question
LIMIT 5

关于问题的LEFT JOIN将允许表示问题,即使没有留下任何评论。

如果您有任何问题,请与我们联系。

答案 1 :(得分:0)

快速查看它,我会这样做:

SELECT q.question_id, count(c.comment) from questions as q left join 
comments as c on q.question_id=c.question_id left join user as u on 
c.user=u.user where u.status=1 group by q.question_id

答案 2 :(得分:0)

SELECT question, count(*) as total_comments, T1.user 
FROM T1, T2, T3
WHERE T1.customer_id = T3.user 
  AND T3.status = 1,
  AND T1.question_id = T2.question_id
GROUP BY T2.user 
ORDER BY question_id DESC
LIMIT 5

T1,T2,T3是按其显示顺序排列的表格。

答案 3 :(得分:0)

SELECT      question_id as question, count(c.comment) as 'total comments', q.customer_id as user
FROM        (SELECT * 
            FROM question
            ORDER BY question_id DESC
            LIMIT 5) as q LEFT JOIN 
            comment as c using(question_id) LEFT JOIN
            user as u using(user) 
WHERE       u.status=1 
GROUP BY    q.question_id
ORDER BY    question_id DESC