匹配多行时选择mysql

时间:2012-12-05 04:39:16

标签: mysql

我有一个项目,我只需要选择以某种方式回答某些问题的用户(基于过滤器)。

过滤表(过滤器)如下所示

   question |   answer  

   Q1       |    A  
   Q2       |    B 

用户表(答案)如下所示

user | question | answer  

  1  |    Q1    |    A  
  1  |    Q2    |    D  
  2  |    Q1    |    A  
  2  |    Q2    |    B 

如何从用户表中仅选择与过滤器匹配的用户?
我试过了

"SELECT user FROM answers WHERE (question = Q1 AND answer = A) 
             AND (question = Q2 AND answer = B)" 

它不起作用 - 我得到一个空的结果。谢谢。

3 个答案:

答案 0 :(得分:3)

在您的查询中,您要求获取不存在的数据。您正在尝试让具有这两种组合的用户。

试试这个

SELECT user FROM answers WHERE (question = 'Q1' AND answer = 'A') 
         OR (question = 'Q2' AND answer = 'B') 

答案 1 :(得分:2)

试试这个:

Select 
DISTINCT(userId)
from user_table ut
inner join filtertable ft on (ut.question=ft.question and ut.answer=ft.answer)

答案 2 :(得分:1)

试试这个

select answers.user
from filter, answers
where filter.question=answers.question and filter.answer=answers.answer
group by answers.user having count(answers.question)=2

select user
from answers
where user not in 
(select distinct a.user from answers a, filter f 
where a.question=f.question and a.answer!=f.answer)