2015-09-26 145 views
2

我需要從另一個表中獲取帖子圖像的多個帖子,每個帖子都有不同的圖像數量。像POST1有10幅圖像,POST2有5張圖片mysql - 在子查詢中獲取多行

我的兩個表是imagepost

post結構

|title |desc |date |postid|... 
|title1|desc1|date1| 1 |... 
|title2|desc2|date2| 2 | 
. 
. 
. 

image結構

|hash |hits |timestamp |userid |postid|... 
|hash1 |hits1|timestamp1|userid1| 1 |... 
|hash2 |hits2|timestamp2|userid1| 3 |... 
|hash3 |hits3|timestamp3|userid1| 2 |... 
|hash4 |hits4|timestamp4|userid1| 1 |... 
. 
. 
. 

我需要獲取職位與他們的圖像,postid是獲取圖像的帖子的關鍵。

我這樣做,但它不給我正確的結果。

SELECT `title`,`desc`,`date` FROM `img`.`post` AS a 
INNER JOIN 
(SELECT `hash`,`hits`,`timestamp`,`userid`,`postid` FROM `img`.`image` WHERE `postid` IS NOT NULL) 
AS b 
WHERE a.`postid` IS NOT NULL 

我得到的結果爲

mysqli_stmt_bind_result($prepare, $title,$desc,$date); 

不是

mysqli_stmt_bind_result($prepare, $title,$desc,$date,$hash,$hits,$timestamp,$userid,$postid); 

這給了錯誤,因爲沒有綁定變量的不匹配。

我需要得到後的圖像陣列的

$hash,$hits,$timestamp,$userid,$postid 

請參閱和建議的方式來做到這一點。

+0

您需要包括所有來自主查詢的'SELECT'子句中的子查詢的列。 – Barmar

+0

@Barmar能否提供一個例子來說明如何去做。 –

+0

爲什麼'images'表中的所有行都相同,除了postid? – Barmar

回答

1

您需要在子查詢的主查詢的SELECT子句中包含所有列,因爲它定義了主查詢返回的內容。此外,不需要子查詢,只需執行普通的JOIN並將WHERE置於主查詢中即可。

您還錯過了ON子句,該子句指定加入兩個表的條​​件。

SELECT a.title, a.desc, a.date, b.hash, b.hits, b.timestamp, b.userid, b.postid 
FROM post AS a 
INNER JOIN image AS b ON a.postID = b.postID 

你可以把圖像信息轉換成PHP代碼的數組:

$post_data = array(); 
while ($prepare->fetch()) { 
    if (!isset($post_data[$postid])) { 
     $post_data[$postid] = array('title' => $title, 'desc' => $desc, 'date' => $date, 'images' => array()); 
    } 
    $post_data[$postid]['images'][] = array('hash' => $hash, 'hits' => $hits, 'timestamp' => $timestamp, 'userid' => $userid); 
} 

您也可以使用GROUP_CONCAT單行中的所有圖像信息。

SELECT a.title, a.desc, a.date, a.postid, 
     GROUP_CONCAT(b.hash ORDER BY b.timestamp) AS hash, 
     GROUP_CONCAT(b.hits ORDER BY b.timestamp) AS hits, 
     GROUP_CONCAT(b.timestamp ORDER BY b.timestamp) AS timestamp, 
     GROUP_CONCAT(b.userid ORDER BY b.timestamp) AS userid 
FROM post AS a 
INNER JOIN image AS b ON a.postID = b.postID 
GROUP BY a.postID 

在結果中,$hash$hits$timestamp,並$userid將是逗號分隔的列表,並且可以使用explode()在PHP他們分成數組。

+0

這種方式的帖子一遍又一遍地重複該帖子中的每張圖片 –

+0

如果帖子中有多張圖片,您將如何列出所有圖片而不必在每一行重複帖子。 – Barmar

+0

我不希望帖子重複,只想要在每篇文章的單個帖子中的所有圖像。 –

1

嘗試下面的代碼,

SELECT a.title, a.desc, a.date, b.hash, b.hits, b.timestamp, b.userid, b.postid 
FROM post AS a 
INNER JOIN image AS b ON a.postID = b.postID GROUP BY a.postid 
+0

這隻會爲每個帖子獲取一張圖片,而不是所有圖片。 – Barmar