0

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

  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 由多个作者撰写,则每次都会与不同的作者一起显示不止一次。我想做的是让每本书后面跟着一系列作者

<html>
<body>

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

mysql_select_db("mydb", $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");


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

3 回答 3

0

这是一个可以解决问题的查询:

SELECT books.title, authors.fname, authors.lname FROM books LEFT JOIN
book_authors ON books.book_id = book_authors.book_id LEFT JOIN authors
ON authors.author_id = book_authors.author_id

您必须仔细检查 book_id 是否与行作者相同。

另一种方法是首先选择书籍,然后在您的 foreach 循环中,通过 book_authors 表查找该书的作者。

另一件需要注意的是mysql_*函数已被弃用,您应该考虑使用mysqli_*PDO

于 2012-10-19T23:21:35.950 回答
0

您的 sql 查询不正确。它需要像这样格式化。

SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name

SELECT books.title, authors.fname, authors.lname FROM books INNER JOIN authors ON books.book_id = authors.book_id

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

于 2012-10-19T23:23:02.613 回答
0

尝试group_concat

SELECT books.title, group_concat(concat(authors.fname,' ',authors.lname) AS Authors
FROM books, book_authors, authors  
WHERE books.book_id = book_authors.book_id 
AND authors.author_id=book_authors.author_id
GROUP BY books.title

然后在 PHP

  while($row = mysql_fetch_array($result1))
  {
     print "<h3>Book Name:</h3>";
     echo $row ['title'];
     print "<br />";
     $authors = explode($row['Authors']); //array of authors

     for($authors as $author)
     {
        echo($author.'<br/>')
     }
   }

您可以改用 JOIN

SELECT books.title, GROUP_CONCAT(authors.fname) AS Authors 
FROM books
LEFT JOIN book_authors ON books.book_id = book_authors.book_id
LEFT JOIN authors ON book_authors.author_id = authors.author_id
GROUP BY books.title
于 2012-10-19T23:26:14.357 回答