使用三个表的Mysql连接查询
我用了三张桌子。第一个表中记录了客户问题使用三个表的Mysql连接查询,mysql,Mysql,我用了三张桌子。第一个表中记录了客户问题 customer_id | question | question_id ---------------------------------------------- 58 | question 4 | 4 41 | question 5 | 5 37 | question 3 | 3 SELECT question
customer_id | question | question_id
----------------------------------------------
58 | question 4 | 4
41 | question 5 | 5
37 | question 3 | 3
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
第二个表中记录了与第一个teble中的问题相关的评论
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
我如何进行一个查询,结果是最后五个问题的列表,按问题id和每个问题相关的评论总数排序。这些问题和意见只能由第三个表中状态为“1”的用户提出
本例中的结果应如下所示:
question | total comments | user
-----------------------------------------------
question 5 | 2 | 41
question 4 | 2 | 58
快看一下,我会这样做:
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
我有理由肯定这是正确的,尽管我这里没有数据来验证
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
问题的左连接将允许问题被表示,即使没有对其留下任何评论
如果你有任何问题,请告诉我
customer_id | question | question_id
----------------------------------------------
58 | question 4 | 4
41 | question 5 | 5
37 | question 3 | 3
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是有问题的表格,它们的显示顺序是正确的。因此,我在问题列中得到空值。使用上述问题中的确切表格?对不起,凯文。在测试您的查询时,我没有输入列的专有名称。这次我正确地测试了它,它在注释表中不计算空值。此查询仅统计有注释的问题的注释。那些没有评论的问题不算在内。啊-谢谢评论。我不知道你需要这些。你知道我怎么做吗?我需要在这个查询中更改什么?@cb0-它不计算注释表中的空值
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