2014-09-22 83 views
0

我有一个表:mysql |有条件的左侧加入请求

record_id user_id type 

1   1   0 
2   1   1 
3   1   0 

问题 //类型 - 0

id title 
1 Title1 
2 Title2 
3 Title3 

答案 // 1型

id question_id 

2 2 

我需要请求获得该输出数据

record_id user_id type title 

1   1   0  Title1 
2   1   1  Title2 
3   1   0  Title3 

我认为这将是有条件的左连接(如果type = 0剩下的问题表连接;如果type = 1,则与答案表一起加入)。 我该怎么做?

回答

1

如果我正确理解你的逻辑,这应该给你正在寻找的结果是:

SELECT 
    v.record_id, 
    v.user_id, 
    v.type, 
    COALESCE(q1.title, q2.title) as title 
FROM 
    votes v LEFT JOIN question q1 
    ON v.type=0 AND v.record_id=q1.id 
    LEFT JOIN answer a 
    ON v.type=1 AND v.record_id=a.id 
    LEFT JOIN question q2 
    ON a.question_id=q2.question_id 
0
SELECT 
    votes.record_id, votes.user_id, votes.type, question.title 
FROM 
    votes 
    LEFT JOIN question ON votes.type=0 AND question.id=votes.record_id 
    LEFT JOIN answer ON votes.type=1 AND answer.id=votes.record_id
+0

难道你更多的细节,这个答案? – Jayan 2014-09-22 07:43:30