两个MySQL查询的常见结果

时间:2017-03-30 20:29:21

标签: mysql sql join inner-join

我希望结合两个MySQL查询,以便返回常见的结果,所以我知道我不打算在这个上使用UNION。我尝试编写一个subselect语句但是没有用到

首先查询:

SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id    
WHERE m.question = 4 and m.answer = 3 and h.page = 4

第二次查询:

SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id    
WHERE m.question = 114 and m.answer = 1 and h.page = 114

合并查询失败:

SELECT s.ses_id FROM session s, multiple, history h
JOIN (
    SELECT session.ses_id
    FROM session, history, multiple
    WHERE multiple.question = 114 and multiple.answer = 1 and history.page = 114 and history.ses_id = session.ses_id and multiple.ses_id=session.ses_id
    ) q1 ON q1.ses_id = s.ses_id
WHERE s.interview = 'lifestyle' and s.finished = 'y' and multiple.page=4 and multiple.answer = 3 and h.page = 4 and h.ses_id = s.ses_id and multiple.ses_id=s.ses_id

多表包含问题和答案,我希望找到那些已经用这些具体答案回答了这两个问题的人的ID。

我意识到这应该很容易,我很可能会过度思考和/或遗漏某些东西。

3 个答案:

答案 0 :(得分:0)

以下简单修改的​​查询可能很有用。

SELECT s.ses_id, h.page, m.question, m.answer FROM session s
INNER JOIN history h on h.ses_id = s.ses_id
INNER JOIN multiple m on m.ses_id = s.ses_id    
WHERE 
( m.question = 4 and m.answer = 3 and h.page = 4 )
OR
( m.question = 114 and m.answer = 1 and h.page = 114 )

不需要合并操作。

答案 1 :(得分:0)

您只需要为historymultiple表加入第二个问题/答案组合的额外时间。

SELECT s.ses_id,
       m1.question, m1.answer, h1.page,
       m2.question, m2.answer, h2.page
FROM session s
INNER JOIN history h1
   ON h1.ses_id = s.ses_id AND h1.page = 4
INNER JOIN multiple m1
   ON m1.ses_id = s.ses_id
   AND m1.question = 4 AND m1.answer = 3
INNER JOIN history h2
   ON h2.ses_id = s.ses_id AND h2.page = 114
INNER JOIN multiple m2
   ON m2.ses_id = s.ses_id
   AND m2.question = 114 and m2.answer = 1
WHERE s.interview = 'lifestyle' and s.finished = 'y'

答案 2 :(得分:0)

如果要查找两个查询的交集,则只需使用IN mysql的set运算符

SELECT s.ses_id, h.page, m.question, m.answer
FROM session s
   INNER JOIN history h on h.ses_id = s.ses_id
   INNER JOIN multiple m on m.ses_id = s.ses_id    
WHERE m.question = 4 and m.answer = 3 and h.page = 4 and s.ses_id 
IN
(
   SELECT s.ses_id
   FROM session s
      INNER JOIN history h on h.ses_id = s.ses_id
      INNER JOIN multiple m on m.ses_id = s.ses_id    
   WHERE m.question = 114 and m.answer = 1 and h.page = 114
)