2014-10-17 57 views
0

我有3個表,例如:後,附加,關係。得到關係,然後從表中獲取 - php和mysql

當我選擇後,比我需要附加文件後,這個職位。

現在我必須從關係表中選擇。因爲附加可以添加到其他職位。

我很容易選擇帖子,那麼現在選擇附件的最佳方式是什麼?

post表:

+----+--------------+-------------+ 
| id | post_title | post_text | 
+----+--------------+-------------+ 
| 1 | test title 1 | test text 1 | 
| 2 | test title 2 | test text 2 | 
+----+--------------+-------------+ 

attach表:

+----+-------------------------------+ 
| id | url       | 
+----+-------------------------------+ 
| 1 | http://xxxxxx.ir/img/logo.png | 
| 2 | http://xxxxxx.ir/img/tut.png | 
+----+-------------------------------+ 

relation表:

+-----+-----+ 
| src | dst | 
+-----+-----+ 
| 1 | 1 | 
| 1 | 2 | 
+-----+-----+ 

和我試過SQL代碼:

SELECT dst FROM relation where src = 1 ; 

,比我在PHP破滅後:

$ids = implode($result); 

那麼我的最終查詢:

SELECT * FROM attach WHERE id IN($ids) ; 

我需要更好的方法和SQL。

+0

是否有一個原因,關係沒有直接存儲在'attach'表中? 「attach」行可以與多個「post」行關聯嗎? – hukir 2014-10-17 22:09:43

+0

是的你認爲替換標籤附加一個標籤或附加可以添加到許多職位而不是一個。 – 2014-10-17 22:15:38

回答

1

您可以使用JOIN從附加表中引入數據。

SELECT r.src, a.* FROM relation AS r JOIN attach AS a ON r.src=a.id WHERE r.src = 1; 
+0

Prefect Bro,你可以給Join教程提供參考嗎? – 2014-10-17 22:29:26

+1

http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/ 和 http://www.halfgaar.net/sql-joins-are-easy是很好的資源 – hukir 2014-10-17 22:33:23