2016-03-12 91 views
0

我用下面的代碼來從數據庫中獲得PDO增值SQL結果

if(!empty($books_ids)) 
{ 
    $books_ids_in = implode(',', array_fill(0, count($books_ids), '?')); 

    $query = "SELECT 
     b.id, 
     b.`name`, 
     b.`year`, 
     GROUP_CONCAT(DISTINCT a.`name`) AS author_names, 
     GROUP_CONCAT(DISTINCT s.`name`) AS store_names 
    FROM 
     books AS b 
     LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id 
     LEFT JOIN authors AS a ON a.id = b_a.author_id 
     LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id 
     LEFT JOIN stores AS s ON s.id = b_s.store_id 
    WHERE 
     b.id IN (". $books_ids_in .") 
    GROUP BY b.id 
    ORDER BY b.id"; 

    $stmt = $conn->prepare($query); 
    foreach ($books_ids as $k => $id) { 
     $stmt->bindValue(($k+1), $id); 
    } 

    $stmt->execute(); 
    $results = $stmt->fetchAll(); 
} 

,當我使用$book id爲了這個目的,我想補充一些參數結果表明,例如數據, param = "book"爲每一行。有沒有辦法做到這一點?

回答

0

只要將它傳遞給字符串並將其別名爲列即可。雖然你知道代碼中傳入的值,並通過代碼顯示值......我不確定爲什麼你需要這個...因爲在顯示代碼時可以使用這個值。

$query = "SELECT 
    b.id, 
    b.`name`, 
    b.`year`, 
    GROUP_CONCAT(DISTINCT a.`name`) AS author_names, 
    GROUP_CONCAT(DISTINCT s.`name`) AS store_names, 
    '". $param."' as forEveryRow 
FROM 
    books AS b 
    LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id 
    LEFT JOIN authors AS a ON a.id = b_a.author_id 
    LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id 
    LEFT JOIN stores AS s ON s.id = b_s.store_id 
WHERE 
    b.id IN (". $books_ids_in .") 
GROUP BY b.id 
ORDER BY b.id"; 
+0

謝謝!原因是,我有3種不同的過濾器 - 「書籍」,「作者」和「商店」(「選擇」列表),我可以一次使用它們或僅使用它們中的一個或兩個,然後我需要從每個過濾器的不同查詢中獲取數據的數據(我猜,我需要UNION在一個查詢中加入所有的SELECT),但是在結果的每一行中,我需要以某種方式添加我用來獲得這一行的過濾器。 (其實,可能是愚蠢的,但我不知道其他方式來做到這一點) – Heidel