我有以下表格:
表名 ----- | 表格字段
书籍------------- | book_id,book_title作者---------- | author_id,author_name
books_authors - | author_id,book_id
用户------------- | user_id,user_name
评论-------- | comment_id,评论
comments_users | comment_id,user_id,book_id,date
我需要显示书名,作者以及本书发布的所有评论(我需要显示用户名,日期,评论)。 我用两个不同的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
这个返回用户名,评论和评论发布的日期。 任何人都可以解释我如何将它们加入到一个查询中?提前致谢
答案 0 :(得分: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
答案 1 :(得分: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
希望这是你想要实现的目标。