根据条件从多个表中获取数据

Get data from multiple tables based on condition

我需要从 3 个不同的 mysql 表中获取一些数据,如下所示。

 +-----------------------------------+      
 | Questions                         |      
 -------------------------------------      
 | id: int(8)                        |      
 | -- data we don't care about here  |      
 | question: TEXT                    |      
 +-----------------------------------+    

 +--------------------------+               
 |Answers                   |               
 +--------------------------+               
 | id: int(8)               |               
 | -- other data            |               
 | answer: TEXT             |               
 +--------------------------+    

 +-----------------------------------+      
 |Votes                              |      
 +-----------------------------------+      
 | id: int(8)                        |      
 | step: tinyint(1)                  |      
 | answerId: int(8)                  |      
 +-----------------------------------+      

我需要得到每个问题得票最多的答案以及该答案的得票数。

我能想到的最佳查询是:

SELECT question, answer, count(votes.id) votesCount FROM questions INNER JOIN answers ON questions.id = answers.questionId INNER JOIN votes ON answers.id = votes.answerId;

然而这是错误的,因为它总是 returns 一个包含第一个问题、随机答案和总票数的结果。

您的直接问题是您的查询缺少 group by 子句。所以它 returns 只有一行,包含总票数和任意选择的问题和答案。

如果您是 运行 MySQL 8.0,这很容易通过聚合素和 window 函数完成:

select question, answer, votescount
from (
    select 
        q.question, 
        a.answer, 
        count(*) votescount,
        rank() over(partition by q.id order by count(*) desc) rn
    from questions q
    inner join answers a on q.id = a.questionid 
    inner join votes on a.id = v.answerid
    group by q.id, q.question, a.id, a.answer
) t
where rn = 1

在早期版本中,它有点复杂。一种选择是使用 having 子句过滤聚合结果集,该子句 returns 每个组的最高计数:

select 
    q.question, 
    a.answer, 
    count(*) votescount,
    rank() over(partition by q.id order by count(*) desc) rn
from questions q
inner join answers a on q.id = a.questionid 
inner join votes on a.id = v.answerid
group by q.id, q.question, a.id, a.answer
having count(*) = (
    select count(*)
    from answers a1
    inner join votes v1 a1.id = v1.answerid
    where a1.questionid = q.id
    group by a1.id
    order by count(*) desc
    limit 1
)