dsc71976 2015-05-23 22:19
浏览 34
已采纳

是否可以在单个查询中将多对多关系与一对多关系组合在一起?

I have a MOVIE table that includes a many to many relationship with a genre as well as a review table that has a one to many relationship. AKA, a movie can have many genres and a genre can have many movies. A movie can have many reviews.

My problem is that as I'm trying to display all of the data from the database I want to display the title, genres associated, and then all of the reviews. I can't seem to do this with just the query, so I started to add my own logic, but that didn't work for me either. I keep thinking that there must be some way to combine the logic into one query.

Here is what I have so far:

$query2 = "SELECT * FROM movie m 
JOIN moviegenre mg ON m.id = mg.movieid 
JOIN genre g ON g.id = mg.genreid
JOIN review r ON r.movieid = m.id
WHERE m.id = mg.movieid";

$title = "starting";
$display = true;
foreach ($db->query($query2) as $row2)
{
    if ($title != $row2['title']) 
    {
        $title = $row2['title'];
        echo '<h2 id="title">' . $row2['title'] . " (" . $row2['year'] 
             . ')<br/><hr/></h2><h4> <u>- Genres - </u><br/>';
        $display = false;
    }
    echo $row2['name'] . '  <br/>  ';

    if ($display == false)
    {
        $display = true;
        echo "<h4 id=\"rating\">" . $row2['rating'] . " stars<br/> " . $row2['subject'] . "<br/>" . "<h5 id=\"rating\">" . $row2['content'] . "</h5></h4>";
    }
} 
echo '</h4>';

And here is the result. Note, it can only include one review and the formatting is pretty ugly. I know that this is really ugly code, it's just been me trying to fix errors in roundabout ways.

Raiders of the Lost Ark (1981)

  • Genres - Action 5 stars Great Movie

This movie never gets old

Adventure

  • 写回答

1条回答 默认 最新

  • doushe2513 2015-06-02 05:20
    关注

    I found an answer while reading a few days later. I learned about joins and realized that they were exactly what I was looking for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 MATLAB四叉树处理长方形tif文件
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了