简体   繁体   中英

How can I display each film title only once?

I'm currently using mySQL in PHP. My task is to list all actors for each film that comes up from a given search. The search and results work fine. However, I need to change the display of the results.

$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";
}

With the above code, I'm getting this:

"The following movies match the filter value: "choco".

BUTTERFLY CHOCOLAT stars NICK STALLONE
BUTTERFLY CHOCOLAT stars MENA TEMPLE
BUTTERFLY CHOCOLAT stars KIM ALLEN
BUTTERFLY CHOCOLAT stars LISA MONROE
BUTTERFLY CHOCOLAT stars ED GUINESS
BUTTERFLY CHOCOLAT stars BURT TEMPLE
BUTTERFLY CHOCOLAT stars MARY KEITEL
CHOCOLAT HARRY stars JOE SWANK
CHOCOLAT HARRY stars RIP CRAWFORD
CHOCOLAT HARRY stars KIRK JOVOVICH
... ... "

When I should be getting this:

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

CHOCOLATE HARRY stars RIP CRAWFORD, JANE JACKMAN, ... ...

I've tried SELECT DISTINCT but that only makes it more complicated.

You will need to GROUP BY Film & then use the Group_Concat function

$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;";

and modify the loop to

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

You must group the results by the film name. Use the 'Group By' clause just before the 'Order By' clause that you have used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM