SQL语句/ php代码为一本书处理许多作者

时间:2012-10-03 01:49:33

标签: php mysql sql

我会尽量简单。我有一张桌子给我的书,一张给作者,还有一张联络表,上面有我的书中带有作者ID的身份证。

现在我的问题是,在这本书有很多作者的情况下,我不想多次列出这些书。我可以使用Group By,但我正在寻找一种方法来列出该书一次,而不是只显示一位作者,如果它有多个,我想在同一个列表中添加其他作者

白天真的想过这个,我想不出一个好办法。非常感谢任何帮助!

谢谢!

3 个答案:

答案 0 :(得分:4)

我认为你要找的是GROUP_CONCAT

SELECT b.Name, GROUP_CONCAT(a.Name) AS Authors
FROM Book b 
    INNER JOIN BookAuthor ba
    ON b.ID = ba.BookID
    INNER JOIN Author a
    ON ba.AuthorID = a.ID
GROUP BY b.Name;

提供输出

50 Shades of Grey                                           EL James
Design Patterns: Elements of Reusable Object-Oriented Software  Ralph
Johnson,Erich Gamma,John Vlissides,Richard Helm
Harry Potter and the Goblet of Fire                         JK Rowling 
Harry Potter and the  Philosopher`s Stone                   JK Rowling

SQL Fiddle here

答案 1 :(得分:1)

做两个SQL语句。像这样......

$sql = "SELECT id, name FROM books";

foreach ($conn->query($sql) as $book) {
    $sql = "SELECT a.name
            FROM authors a, author_books ab
            WHERE ab.book_id = $book['id']
            AND ab.author_id = a.id";

    foreach ($conn->query($sql) as $author) {
        echo $row["name"];
    }
}

干杯

答案 2 :(得分:0)

见这个例子

CREATE TABLE book
(
bID INT,
bName VARCHAR(100),
PRIMARY KEY (bID)
);
--
CREATE TABLE author
(
aID INT,
aName VARCHAR(100),
PRIMARY KEY (aID)
);

CREATE TABLE book_author
(
aID INT ,
bID INT ,
PRIMARY KEY (aID,bID),
FOREIGN KEY (aID) REFERENCES author(aID),
FOREIGN KEY (bID) REFERENCES book(bID)
); 

INSERT INTO author (aID, aName) VALUES
    (1, 'The Doctor'),
    (2, 'Dalek1'),
    (3, 'Dalek2'),
    (4, 'Amy'),
    (5, 'Rory');

INSERT INTO book (bID, bName) VALUES
    (1, 'The Book of Crazy'),
    (2, 'Is Time Really Time'),
    (3, 'I Think without Pants'),
    (4, 'Perfection'),
    (5, 'Rise of the Daleks ');

INSERT INTO book_author (aID, bID) VALUES
    (4, 1),
    (1, 2),
    (4, 2),
    (5, 2),
    (1, 3),
    (2, 4),
    (2, 5),
    (3, 5);

----------
--the query
SELECT DISTINCT b.bName
FROM book b,author a,book_author ba
WHERE ba.aID=a.aID and ba.bID=b.bID and (a.aName = 'Amy' or a.aName='The Doctor')

--------------
--output
--Is Time Really Time
--I Think without Pants
--The Book of Crazy

您需要做的就是使用DISTINCT关键字 并遵循贾斯汀伍德的方法