dongping4461 2013-10-20 14:23
浏览 57
已采纳

MySQL如何使用来自不同表的一个查询获得两个结果

I have the following tables:


table name -----| table fields

books -------------| book_id, book_title

authors ---------- | author_id, author_name

books_authors - | author_id, book_id

users ------------- | user_id, user_name

comments -------- | comment_id, comment

comments_users | comment_id, user_id, book_id, date


I need to show the book title, its authors, and all the comments posted for this book (I need to show user name, date, comment). I make do it with two different sql queries, but I don't know how to do it with just 1 query. Here are the two queries:

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

this one returns the name and authors of book with 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

this one returns the user name, comment, and the date the comment was posted. Can anyone explain me how can I join them into one query? Thanks in advance

  • 写回答

2条回答 默认 最新

  • dongzhong2018 2013-10-20 14:56
    关注

    This arranged query should suffice, it will display results as you want :

    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条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题