这是我的表结构:
-- 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
在这种情况下的确切运作方式。
我有一个qanda
表的ID,我总是想要一个标题。该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 :(得分: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)
答案 1 :(得分:1)
与Serg相似;但如果您遇到这种情况,使用左连接将允许带有out(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
答案 2 :(得分: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;