2017-07-14 40 views
0

这里是我的表结构:如何加入null?

-- qanda (stands for questions and answers) 
+----+---------+-----------------------------------------------+--------------+ 
| id | title |      content     | question_id | 
+----+---------+-----------------------------------------------+--------------+ 
| 1 | title1 | this is a question       | NULL   | 
| 2 | NULL | this is an answer        | 1   | 
| 3 | NULL | this is another answer      | 1   | 
| 4 | title2 | this is another question      | NULL   | 
| 5 | NULL | this is an answer for the second question  | 4   | 
| 6 | NULL | this is another answer for the first question | 1   | 
+----+---------+-----------------------------------------------+--------------+ 

我知道,这将是更好,如果我保持两个不同的表中的问题和答案。但现在我只是想了解JOIN在这种情况下的工作原理。


我有一个ID为qanda表,我总是想要一个标题。该ID可能是问题的ID或答案的ID。我怎样才能做到这一点?


我想是这样的:

SELECT t1.title 
FROM qanda t1 
INNER JOIN qanda t2 
ON t1.id = t2.question_id 
WHERE t1.id = :id 

我的查询没有匹配。这里是预期结果的一些样品:

-- :id = 1 
+--------+ 
| title1 | 
+--------+ 

-- :id = 2 
+--------+ 
| title1 | 
+--------+ 

-- :id = 4 
+--------+ 
| title2 | 
+--------+ 

-- :id = 5 
+--------+ 
| title2 | 
+--------+ 

-- :id = 6 
+--------+ 
| title1 | 
+--------+ 
+0

创建表格的脚本 – etsa

+0

@etsa请问您需要什么?表格结构在我的问题中非常清楚。 –

+3

这对你来说很清楚......不适合我......如果你需要帮助,请发布要求 – etsa

回答

1

与Serg类似;但如果您有这样的情况,使用左连接将允许在结果中出现无结果(W/O)答案的问题。

SELECT distinct coalesce(t2.title, t1.title) as title 
FROM qanda t1 
LEFT JOIN qanda t2 
    ON t1.id = t2.question_id 
WHERE (t1.id = 1 or T2.ID = 1) 
    and Type = 0; 

如果我们可以假设一个标题只存在于问题上并且没有答案将会有标题。

我认为这很难维护,它应该更快,因为它消除了连接(有点存在可以提早逃脱连接将无法和因为限制发生在子查询我们只有1条记录真正处理加入)和独特。

SELECT t1.title as title 
FROM qanda t1 
WHERE (EXISTS (SELECT 1 
       FROM qanda t2 
       WHERE ID = 1 
       and t1.ID = t2.question_id) --correlated subquery 
      or t1.id = 1) 
    and Type = 0 
+0

是否“无”表示“无”? –

+0

对不起,这是正确的。我会拼出来。 – xQbert

+0

另外,'distinct'是多余的,因为'id'是PK,对吧? –

3

的2联合查询

SELECT t1.title 
FROM qanda t1 
WHERE t1.id = :id and t1.title IS NOT NULL 
UNION 
SELECT t1.Title 
FROM qanda t2 
JOIN qanda t1 
ON t1.id = t2.question_id 
WHERE t2.id = :id 

或者

SELECT DISTINCT t1.title 
FROM qanda t1 
JOIN qanda t2 
ON t1.id = t2.question_id 
WHERE :id in (t2.id, t1.id) 
+0

是的,这是唯一的工作答案,似乎是一个沉重的查询。不管怎么说,还是要谢谢你。 upvote –

+0

好..我喜欢你的替代方法。你认为哪一个更好?你的第一种方法还是第二种? –

+0

第二个应该跑的更快,只是一个猜测。 – Serg

0

你可以尝试这样的事情:

SELECT title 
FROM qanda 
INNER JOIN (
    SELECT DISTINCT COALESCE(t1.question_id, t1.id) AS ID 
    FROM qanda t1 
    WHERE :id IN(t1.question_id=:id, t1.id) 
    ) B ON qanda.id = B.ID; 
+0

[It does not work](http://sqlfiddle.com/#!9/cb083c/20) –

+0

你为什么要用'COALESCE'而不是'OR'? –

+0

答案已更新。 – etsa