我有3张表如下
问题(q_id,question,cat_id)
答案(a_id,q_id,answer,user_id,rate)
用户(user_id,用户名)
现在我想要一个特定类别的所有问题及其答案,如果退出的答案率最高,那个人的用户名就是。
我正在使用以下查询来执行此操作,但它没有给我那个回复率最高的答案。
select c.*,d.username,d.user_id
from users d
join (
SELECT b.*,a.question
FROM `questions` a
left join answers b
on a.q_id=b.q_id
WHERE a.`cat_id` = 8
group by b.q_id) c
on c.user_id=d.user_id
答案 0 :(得分:0)
如果尝试这样做:
SELECT c.*,d.username,d.user_id
FROM users d
JOIN (
SELECT b.*,a.question
FROM `questions` a
LEFT JOIN (
SELECT t1.*
FROM answers t1
JOIN (
SELECT q_id, max(rate) AS rate FROM answers GROUP BY q_id
) t2
ON t1.q_id = t2.q_id AND t1.rate = t2.rate
) b ON a.q_id=b.q_id
WHERE a.`cat_id` = 8
GROUP BY b.q_id) c ON c.user_id=d.user_id
因为您没有提供一些示例数据和所需的结果,所以这可能无法按预期工作。
<强> 编辑: 强>
SELECT q.*, a.*
FROM questions q
LEFT JOIN (
SELECT t1.*, u.user_id, u.username
FROM answers t1
INNER JOIN questions t3 ON t1.q_id = t3.q_id AND t3.cat_id = 8
INNER JOIN (
SELECT q_id, max(rate) AS rate FROM answers GROUP BY q_id
) t2
ON t1.q_id = t2.q_id AND t1.rate = t2.rate
LEFT JOIN users u ON t1.user_id = u.user_id
ORDER BY t1.a_id LIMIT 1
) a
ON q.q_id = a.q_id
WHERE q.cat_id = 8