0

我有以下表格:


表名-----| 表字段

书籍------------| book_id, book_title

作者 ---------- | author_id, author_name

book_authors - | author_id, book_id

用户 ------------- | 用户 ID,用户名

评论-------- | comment_id,评论

评论用户 | comment_id、user_id、book_id、日期


我需要显示书名、作者以及为这本书发布的所有评论(我需要显示用户名、日期、评论)。我用两个不同的 sql 查询来做到这一点,但我不知道如何只用 1 个查询来做到这一点。这是两个查询:

SELECT * FROM books
INNER JOIN books_authors
ON books.book_id=books_authors.book_id
INNER JOIN authors
ON books_authors.author_id=authors.author_id
WHERE books.book_id=7

这个返回 id=7 的书名和作者。

SELECT `user_name`, `comment`, `date`
FROM comments_users
INNER JOIN comments ON comments_users.comment_id = comments.comment_id
INNER JOIN users ON comments_users.user_id = users.user_id
WHERE comments_users.book_id=7

这个返回用户名、评论和发表评论的日期。谁能解释我如何将它们加入一个查询?提前致谢

4

2 回答 2

2

这个安排好的查询就足够了,它会根据需要显示结果:

SELECT books.book_title, authors.author_name, comments.comment FROM books
INNER JOIN books_authors
ON books.book_id=books_authors.book_id
INNER JOIN authors
ON books_authors.author_id=authors.author_id
LEFT JOIN comments_users ON comments_users.book_id = books.book_id
INNER JOIN comments ON comments_users.comment_id = comments.comment_id
INNER JOIN users ON comments_users.user_id = users.user_id
WHERE books.book_id=7
于 2013-10-20T14:56:23.047 回答
1

你不能只加入这两个查询中的所有表吗?

SELECT `books.book_id`, `books.book_title`, `comments_users.user_name`,
`comments_users.comment`, `comments_users.date` 
FROM books
INNER JOIN books_authors ON books.book_id=books_authors.book_id
INNER JOIN authors ON books_authors.author_id=authors.author_id
INNER JOIN comments_users ON comments_users.book_id = books.book_id
INNER JOIN comments ON comments_users.comment_id = comments.comment_id
INNER JOIN users ON comments_users.user_id = users.user_id
WHERE books.book_id=7

希望这是您想要实现的目标。

于 2013-10-20T14:55:34.763 回答