如何获取相关行的值?

时间:2016-06-05 16:04:40

标签: mysql sql join

我有一张这样的表:

// QandA
+----+----------+----------------+------+---------+-----------+
| id | subject  | acceptedanswer | type | related | id_author |
+----+----------+----------------+------+---------+-----------+
| 1  | subject1 | NULL           | 0    | NULL    | 123       |
| 2  |          | 1              | 1    | 1       | 452       |
| 3  | subject2 | NULL           | 0    | NULL    | 635       |
| 4  |          | 1              | 1    | 3       | 432       |
| 5  |          | NULL           | 1    | 1       | 246       |
+----+----------+----------------+------+---------+-----------+

/* columns explanations:
- acceptedanswer can be NULL, 0, 1. (0 and NULL are identical). (it is NULL for questions)
- type is 0 for questions and 1 for answers.
- related is NULL for questions. For answers is containing the number of its own question
*/

我有两个参数:

  • id答案的数量:$id = 5
  • 该答案的{li> id_author $id_author = 246

现在我想尝试这两件事:

  • 其欠题的主题
  • 指定任何接受的答案都有自己的问题。

以下是我的查询:

SELECT t2.subject
FROM qanda t1
JOIN qanda t2 ON t1.related = t2.id AND t2.type = 0
WHERE t1.id = $id AND t2.id_author = $id_author

当前结果:

+----------+
| subject1 |
+----------+

预期结果:

+----------+---+
| subject1 | 1 |
+----------+---+
--           ^ this 1 means the question of this answer has a accepted answer
--           ^ this should be 0 if there isn't any accepted answer for that question

我该怎么做?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT t2.subject, max(COALESCE(t3.accepted, 0))
FROM qanda t1
INNER JOIN qanda t2 ON t1.related = t2.id AND t2.type = 0
INNER JOIN qanda t3 ON t1.related = t3.related
WHERE t1.id = $id AND t2.id_author = $id_author
GROUP BY t3.related
但是,我不确定我是否理解你的意图。 COALESCE删除空值,max()查看是否已接受任何答案。我假设只有答案在related列中具有非空值。

另外,也许最好不要在同一张桌子上保留不同的东西?

答案 1 :(得分:1)

如果您想知道答案id = 5回答的问题是否有接受的答案,并假设(如评论中所述)每个问题只能有一个被接受的答案,那么这样的话(注意:两个加入)应该工作......

SELECT x.subject
     , y.id IS NOT NULL has_accepted
  FROM qanda x
  LEFT
  JOIN qanda y
    ON y.related = x.id
   AND y.type = 1
   AND y.acceptedanswer = 1
  JOIN qanda z
    ON z.related = x.id
 WHERE x.type = 0 
   AND z.id = 5;