2016-08-14 5 views
2

Ich habe zwei Tabellen: qanda und comment. Hier ist die Struktur von ihnen:Wie bekomme ich ID-Nummer von einer anderen Tabelle?

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

Ich habe nur ein id von comment Tisch. Dies ist meine aktuelle Abfrage:

SELECT post_id FROM comment WHERE id = :id 

Stromausgang:

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

Aber ich brauche auch die ID der eigenen Frage zu wählen. Das ist also erwartetes Ergebnis:

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

Nun, wie kann ich das tun?

Antwort

1

Wenn ich richtig zu verstehen, müssen Sie nur die Tabellen join zusammen:

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

Vielen Dank. upovote –

1

Unter der Annahme, id in qanda Tabelle post_id und verwandt ist die question_id ist, diese Abfrage sollte den Job erledigt bekommen:

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

Vielen Dank .. upote –

Verwandte Themen