2016-07-08 40 views
-1

我有3個表如下爲了先再組通過在MySQL

問題(q_id,問題,CAT_ID)

回答(A_ID,q_id,答案,USER_ID,率)

用戶(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

如果嘗試一下這個:

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 
+0

如何'之外了'無濟於事派生? – Drew

+0

是啊,工作很好,謝謝 –

+0

哦,我明白了,我的眼睛累了,以爲它在外面。我的壞 – Drew