【问题标题】:MySQL simple query about joinMySQL关于join的简单查询
【发布时间】:2017-10-26 03:03:43
【问题描述】:

ERD Image

我是大学。来自韩国的学生,首先对我的英语能力感到抱歉:D

我设计了简单的书店数据库,但我很难编写查询:(我如何使用 ERD 像下面这样打印?

[ISBN, 标题, writer.name, page, price, publisher.name, publish_date, topic, review]

如果作者和主题为 2 或更多,则打印所有元组。你们能帮帮我吗?

【问题讨论】:

标签: mysql


【解决方案1】:

这是一个简单的问题,当您想从连接表中查找任何值时,可以像程序查询一样思考:

需要 customer.address ,基表:book 所以:book join purchache -> join customer -> catch the value # 它会死在这里,让我们去另一个值。

需要 topic.name ,基表:书 所以:预订加入主题 -> 抓住价值 # 下一个

不多说了,让我们来查询吧:

select 
    book.ISBN
    book.title
    book.price
    book.publisher_date
    writer.name as WriterName /* if you need an alias */
    publisher.name as PublisherName /* if you need an alias */
    topic.name as TopicName /* if you need an alias */
    purchase.review
    /* bonus */
    customer.phone_number

 from book 
     left join writer on writer.cook_id = book.id
     left join topic on topic.cook_id = book.id
     left join publisher on publisher.id = book.publisher_id
     left join purchase on purchase.book_id = book.id /* first */
         left join customer on purchase.customer_id = customer.id /* second */

我认为它有效。 :)

【讨论】:

  • 我能再问你 1 个问题吗?我想像这样打印 [writer_name, publisher_name, count] 计数是作家在出版商中出版的书籍数量,我的查询是......选择 writer.name 作为 writer_name,publisher.name 作为 publisher_name from writer natural join book,publisher where book.publisher_id = publisher.id order by writer_name
  • 您的计数(publisher.id),但它是正确的,如果您需要列出多个发布者,则需要按 publisher.id 分组,并且对于加入,如果“发件人”是作家,要接触出版商,你需要加入作家 -> 书 -> 出版商
【解决方案2】:

只是一个快速的模型。我对表结构做了假设。三张表,一张用于书籍,一张用于作者,一张用于评论。

我使用了左连接,因为我假设您将根据这本书进行查询,ISBN 是该表的唯一键。 加入可能需要一些时间来弄清楚,所以如果您需要有关加入的帮助,此站点可能会有所帮助。 https://www.techonthenet.com/mysql/joins.php

select
        boo.ISBN, 
        boo.title, 
        au.author_name,
        boo.pages,
        boo.price,
        boo.publisher,
        boo.publish_date,
        boo.genre,
        rev.review  

        from books as boo
            left join author as au
                on boo.authorID = au.authorID
            left join reviews as rev
                on rev.ISBN = boo.ISBN
        where boo.ISBN = XXXX;

如果您在制作 ERD 本身时需要帮助,如果我误读了最初的问题 this link here

,还有另一篇 stackexchange 文章可能会有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    相关资源
    最近更新 更多