关于获取与一行相关的多行的MySql查询问题

时间:2015-05-16 09:36:00

标签: php mysql sql

我的MySql数据库中有如下表格。

table_books

book_author         book_name                       book_page   book_price  book_published_date book_topic

James Anderson      Introduction to PHP             200         50          1/12/2013           Science
James Anderson      Expert in jQuery                150         40          8/7/2014            Programming
James Anderson      HTML                            200         60          5/9/2012            Web
Richard Benjamin    Successful stories of Business  300         70          4/6/2014            Business
Richard Benjamin    Entrepreneurship                500         80          8/9/2013            Business
Richard Benjamin    Business Studies                100         40          2/5/2012            Business

我想得到如下结果

book_author James Anderson              

book_name           book_page   book_price  book_published_date book_topic  

Introduction to PHP 200         50          1/12/2013           Science 
Expert in jQuery    150         40          8/7/2014            Programming 
HTML                200         60          5/9/2012            Web 




book_author Richard Benjamin                


book_name                       book_page   book_price  book_published_date book_topic  

Successful stories of Business  300         70          4/6/2014            Business    
Entrepreneurship                500         80          8/9/2013            Business    
Business Studies                100         40          2/5/2012            Business

我需要SQL查询。我需要拿一行(book_author)和其他关联行。

由于

1 个答案:

答案 0 :(得分:0)

<?php
    $sqlAuthor = "SELECT DISTINCT book_author FROM book_name";
    $exeAuthor = mysql_query($sqlAuthor);
    if($exeAuthor)
    {
        while($dataAuthor = mysql_fetch_assoc($exeAuthor))
        {
            $sqlBookRec = "SELECT * FROM book_name where book_author='".$dataAuthor['book_author']."'";
            $exeBookRec = mysql_query($sqlBookRec);
            if($exeBookRec)
            {
                echo "Book Author: ".$dataAuthor['book_author'];
                while($dataBookRec = mysql_fetch_assoc($exeBookRec))
                {
                    echo "Book Name".$dataBookRec['book_name'];
                }
            }
        }
    }
?>

试试这个。希望它能起作用。