-3

我有书籍和作者的数据库。这两个实体之间的关系是多对多的,因此它们之间有一个联合表。

  1. bookshas books.book_idas primary, authors.author_idas primary 和联合表book_authors有:book_authors.book_idbook_authors.author_id.

  2. 每本书都有不止一位作者。

我想要做的是有一个 php 页面,在一行中显示每本书,然后在下面显示:author1:....,author2(如果适用)。

我希望我的 php 看起来有点像:

Book Name: THE BOOK NAME
Author(s): joe- John- Sara

我使用了以下代码,问题是它返回单个结果。因此,如果 book1 是由 author1 和 author2 创作的,我只会在结果页面中获得一位作者。这是我使用的代码。

<html>
<body>

<?php
$con = mysql_connect("localhost","yalmuza","e6ddthmu");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("yalmuza", $con);

$result1 = mysql_query("
    SELECT
        books.title, authors.fname, authors.lname
    FROM
        books, book_authors, authors
    WHERE
        books.book_id = book_authors.book_id
        AND authors.author_id=book_authors.author_id
    GROUP BY
        books.book_id
");


while($row = mysql_fetch_array($result1))
  {
print "<h3>Book Name:</h3>";
  echo $row ['title'];
print "<br />";
print "Author(s):";
  echo $row ['fname'];
  echo $row ['lname'];
  echo "<br />";
  }

mysql_close($con);
?>

</body>
</html>
4

1 回答 1

1
SELECT books.* GROUP_CONCAT(author.name SEPARATOR ', ') AS authors
RIGHT JOIN book_authors ON books.id = book_author.book_id
LEFT JOIN author ON book_author.author_id = author.id
GROUP BY book.id

您可以阅读有关如何执行 MySQL 查询的手册: http ://www.php.net/manual/en/pdo.query.php

于 2012-10-19T22:12:35.140 回答