0

我会尽量让它简单。我有一张桌子放我的书,一张桌子放作者,还有一张连接表,其中的 id 来自我的书和作者 ID。

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

白天还真想着这事,也想不出什么好办法。任何帮助是极大的赞赏!

谢谢!

4

3 回答 3

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小提琴在这里

于 2012-10-03T06:47:36.420 回答
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"];
    }
}

干杯

于 2012-10-03T01:58:47.520 回答
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 关键字并遵循 Justin Wood 的方法

于 2012-10-03T03:04:43.597 回答