簡體   English   中英

mysql - 在子查詢中獲取多行

[英]mysql - fetching multiple rows in sub query

我需要從另一個表中獲取帶有帖子圖像的多個帖子,每個帖子都有不同的圖片數量。 就像 post1 有 10 張圖片,post2 有 5 張圖片

我的兩張桌子是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

請查看並建議一種方法。

您需要在主查詢的 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將是逗號分隔的列表,您可以在 PHP 中使用explode()將它們拆分為數組。

試試下面的代碼,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM