我有两个表:qanda
和comment
。以下是它们的结构:
// qanda
+----+----------+----------------------+---------+------+
| id | title | content | related | type |
+----+----------+----------------------+---------+------+
| 1 | a title | a content | NULL | 0 |
| 2 | | a content | 1 | 1 |
| 3 | a title | a content | NULL | 0 |
| 4 | | a content | 1 | 1 |
| 5 | | a content | 3 | 1 |
+----+----------+----------------------+---------+------+
/* type column: "0" means it is a question, "1" means it is a answer
related column: it contains the id number of its own question
*/
// comment
+----+---------+---------+-----------------+
| id | post_id | user_id | content |
+----+---------+---------+-----------------+
| 1 | 1 | 324523 | a content |
| 2 | 5 | 435243 | a content |
+----+---------+---------+-----------------+
我在id
表中只有一个comment
。这是我目前的查询:
SELECT post_id FROM comment WHERE id = :id
当前输出:
// assuming :id = 2
+---------+
| post_id |
+---------+
| 5 |
+---------+
但我还需要选择自己问题的ID。所以这是预期结果:
// assuming :id = 2
+-------------+---------+
| question_id | post_id |
+-------------+---------+
| 3 | 5 |
+-------------+---------+
那我怎么能这样做?
答案 0 :(得分:1)
如果我理解正确,你只需要join
这些表:
SELECT c.post_id, q.related
FROM comment c
join qanda q on c.post_id = q.id
WHERE c.id = :id
答案 1 :(得分:1)
假设qanda表中的id是post_id且相关的是question_id,则此查询应该完成工作:
SELECT qanda.related AS question_id, qanda.id AS post_id
FROM qanda, comment
WHERE comment.id = id AND qanda.id = comment.post_id