0

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

  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

4 回答 4

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 将允许表示问题,即使没有留下任何评论。

如果您有任何问题,请告诉我。

于 2012-05-13T12:20:48.360 回答
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
于 2012-05-13T12:20:44.907 回答
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 是按它们出现的顺序讨论的表格。

于 2012-05-13T12:20:52.217 回答
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
于 2012-05-13T19:01:39.567 回答