如何只显示一次电影片名?

时间:2016-10-12 16:25:42

标签: php mysql

我目前在PHP中使用mySQL。我的任务是列出从给定搜索中出现的每部电影的所有演员。搜索和结果工作正常。但是,我需要更改结果的显示。

$sql = "SELECT f.title, a.first_name, a.last_name 
    FROM film as f, actor as a, film_actor as fa 
    WHERE (f.title LIKE \"%$filter%\") 
    AND fa.actor_id = a.actor_id 
    AND f.film_id = fa.film_id
    ORDER BY f.title;";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "The following movies match the filter value: &quot$filter&quot." . "</strong>" .
     "</div>\n<br><br>\n";

// output data of each row
while(($row = $result->fetch_assoc())) {
    echo 
    $row["title"] . " " . "stars" . " " .
    $row["first_name"] .  " " .
    $row["last_name"] .  
    "</div>\n" . 
    "<br>\n";
}
} else {
echo "0 results";
}

通过上面的代码,我得到了这个:

&#34;以下电影与过滤器值匹配:&#34; choco&#34;。

BUTTERFLY CHOCOLAT主演NICK STALLONE
BUTTERFLY CHOCOLAT明星MENA TEMPLE
BUTTERFLY CHOCOLAT主演KIM ALLEN
BUTTERFLY CHOCOLAT星星LISA MONROE
BUTTERFLY CHOCOLAT明星ED GUINESS
BUTTERFLY CHOCOLAT星星BURT TEMPLE BUTTERFLY CHOCOLAT明星MARY KEITEL
CHOCOLAT HARRY明星JOE SWANK
CHOCOLAT HARRY明星RIP CRAWFORD
CHOCOLAT HARRY主演KIRK JOVOVICH
... ......&#34;

当我得到这个时:

BUTTERFLY CHOCOLAT主演ED GUINESS,MARY KEITEL,LISA MONROE,NICK STALLONE,BURT TEMPLE,MENA TEMPLE

巧克力哈里明星RIP CRAWFORD,JANE JACKMAN, ... ...

我尝试过SELECT DISTINCT,但这只会让它更复杂。

2 个答案:

答案 0 :(得分:1)

你需要GROUP BY电影&amp;然后使用Group_Concat函数

$sql = "SELECT f.title, group_concat(concat(a.first_name, " ", a.last_name)) ActorNames 
FROM film as f, actor as a, film_actor as fa 
WHERE (f.title LIKE \"%$filter%\") 
AND fa.actor_id = a.actor_id 
AND f.film_id = fa.film_id
GROUP BY f.title
ORDER BY f.title;";

并将循环修改为

while(($row = $result->fetch_assoc())) {
echo 
$row["title"] . " " . "stars" . " " .
$row["ActorNames"] .  " " .
"</div>\n" . 
"<br>\n";

答案 1 :(得分:0)

您必须按电影名称对结果进行分组。使用&#39; Group By&#39;条款之前&#39; Order By&#39;您使用过的子句。