php mysql数组结果问题

时间:2012-10-19 23:11:35

标签: php

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

  1. books主要books.book_id,主要authors.author_id为主要,联合表book_authors包含:book_authors.book_idbook_authors.author_id

  2. 每本书都有多位作者。

  3. 我想要做的是拥有一个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>
    

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 来自人 内部联合订单 ON Persons.P_Id = Orders.P_Id ORDER BY Persons.LastName

答案 2 :(得分: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