2016-08-14 14 views
2

私は2つのテーブル:qandacommentを持っています。ここでは、それらの構造は次のとおりです。別のテーブルからID番号を取得するにはどうすればよいですか?

// 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  | 
+----+---------+---------+-----------------+ 

私はcommentテーブルからわずかidを持っています。

SELECT post_id FROM comment WHERE id = :id 

電流出力:これは私の現在のクエリで

// assuming :id = 2 
+---------+ 
| post_id | 
+---------+ 
| 5  | 
+---------+ 

しかし、私はまた、独自の質問のIDを選択する必要があります。

// assuming :id = 2 
+-------------+---------+ 
| question_id | post_id | 
+-------------+---------+ 
| 3   | 5  | 
+-------------+---------+ 

まあ、私はそれをどのように行うことができます。これは期待される結果ですか?

答えて

1

私が正しく理解していた場合、あなただけ一緒にテーブルをjoinする必要があります。qandaテーブルにIDを想定し

SELECT c.post_id, q.related 
FROM comment c 
    join qanda q on c.post_id = q.id 
WHERE c.id = :id 
+0

ありがとうございます。 。アップヴォート –

1

question_id post_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 
+0

ありがとう.. upote –

関連する問題