链接加入目标表

时间:2014-06-20 08:33:24

标签: mysql sql

我有四张桌子

Survey          Question        Responses       Participants
=============   ==============  ==============  =============
id_S            id_Q            id_R            id_P
                id_S            id_Q            id_S
                                id_P
                                id_S
                                Answer

我正在试图找出如何检索给出“D”作为问题#3答案的参与者的所有回复。

这是我对它的第一次嘲笑,但毫不奇怪它不起作用。

SELECT * 
FROM responses r
LEFT JOIN participants p
ON r.id_P = p.id_P
LEFT JOIN responses r2
ON p.id_R = r.id_P
WHERE r.id_S = 1 AND r2.Answer = "D" AND r2.id_Q = 1

由于不起作用,它返回太多记录。 SQL Select * FROM responses WHERE id_S =1将返回1,891条记录,但上面的热点会返回15,128条记录。

显然,我甚至没有关于如何使其发挥作用的正确概念,而且这不是一个简单的语法调整。

2 个答案:

答案 0 :(得分:3)

SELECT  ra.*
FROM    responses rd
JOIN    responses ra
ON      (ra.id_s, ra.id_p) = (rd.id_s, rd.id_p)
WHERE   (rd.id_q, rd.answer) = (3, 'D')

答案 1 :(得分:1)

试试这个:

SELECT r2.* 
FROM Responses r2
     INNER JOIN (Responses r
     INNER JOIN Question q ON r.id_Q = q.id_Q
     INNER JOIN Participants p ON p.id_P = r.id_P) r1 ON r2.id_P = r1.id_P
WHERE q.id_Q = 3
AND r.Answer = 'D';