简体   繁体   中英

MySQLi inner join not working properly

I have a query that select shows alongside with it's rating. But it will not work if there isn't any rates. I want it to work even when it finds zero results on the rating table.

My query is

$shows = $DB->query('SELECT
p.id, p.title, p.cover, p.summary, p.genre, p.year, 
ROUND(AVG(pr.rating), 1) AS rating_average
FROM shows p
INNER JOIN shows_ratings pr
ON pr.showid = p.id');

Change inner join with left join.

Explanation: You are trying to join two table on key which doesn't exist in other table, that's why you are not getting any result in inner join. Whereas left join will return rating as empty when key is not present in rating table.

   $shows = $DB->query('SELECT
    p.id, p.title, p.cover, p.summary, p.genre, p.year, 
    ROUND(AVG(pr.rating), 1) AS rating_average
    FROM shows p
    LEFT JOIN shows_ratings pr
    ON pr.showid = p.id');

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