根据条件交叉表的多行

时间:2018-04-22 13:44:55

标签: mysql

我有一个包含response_id,question_id和answer_id列的表。

我想找到所有匹配多个条件的response_id。例如,以下是一些用例

  1. 用户选择问题1的答案1和问题2的答案2
  2. 用户(问题1的选择答案3和问题2的答案2)或问题3的答案1
  3. 在SQL中,我可以使用INTERSECT和UNION执行此操作,但INTERSECT在MySQL中不可用。有人可以指导我如何解决这个问题吗?

    SQL中的

    示例,这在MySQL中是必需的。

    select distinct(response_id) from table where question_id = 873 AND answer_id = 5269
    intersect
    select distinct(response_id) from table where question_id = 874 AND answer_id = 5273
    intersect
    select distinct(response_id) from table where question_id = 877 AND answer_id = 5286
    

2 个答案:

答案 0 :(得分:1)

MySQL不支持INTERSECT,但我们可以使用EXISTS子句来模拟它:

SELECT DISTINCT response_id
FROM table
WHERE
    question_id = 873 AND
    answer_id = 5269 AND
    response_id IN (
        SELECT DISTINCT response_id FROM yourTable
        WHERE question_id = 874 AND answer_id = 5273) AND
    response_id IN (
        SELECT DISTINCT response_id FROM yourTable
        WHERE question_id = 877 AND answer_id = 5286);

答案 1 :(得分:0)

SELECT DISTINCT * FROM 
(SELECT table.response_id FROM table, data WHERE table.question_id = 873 AND  
table.answer_id = 5269) query1
INNER JOIN
(SELECT table.response_id FROM table, data WHERE table.question_id =874 AND 
table.answer_id = 5273) query2