Answer the question
In order to leave comments, you need to log in
How to make such a database in Mysql?
You need to make a database that stores books and authors and make a query to display authors who have written more than 3 books. I managed to make 2 tables.
authors table
----+--------------+
| id | AuthorName |
+----+--------------+
| 1 | John Smith |
| 2 | Jane Doe |
| 3 | Someone Else |
+----+--------------+
+--------+-----------------------+----------+
| bookId | title | authorId |
+--------+-----------------------+----------+
| 1 | Secret of Everything | 1 |
| 2 | Secret of Nothing | 1 |
| 3 | Secret of Some Things | 1 |
| 4 | No More Secrets | 1 |
| 5 | How to Tame Cats | 2 |
| 6 | How to Tame Dogs | 2 |
| 7 | Just a Book | 3 |
+--------+-----------------------+----------+
mysql> SELECT AuthorName, COUNT(authorId) as authorId
FROM books LEFT JOIN authors ON authorId = id
GROUP BY AuthorName
HAVING authorId >= 3;
Answer the question
In order to leave comments, you need to log in
That's right: the relationship between the tables should be M:M (many to many), since one author can have many books, and one book can have many authors. You have designed a database in which a book can have only one author.
The db will look like this:
CREATE TABLE authors
(
id INT PRIMARY KEY AUTO_INCREMENT,
author_name VARCHAR(100) NOT NULL UNIQUE
);
CREATE TABLE books
(
id INT PRIMARY KEY AUTO_INCREMENT,
book_title VARCHAR(100) NOT NULL
);
CREATE TABLE book_author_id
(
id INT PRIMARY KEY AUTO_INCREMENT,
author_id INT NOT NULL,
book_id INT NOT NULL,
FOREIGN KEY (author_id) REFERENCES authors (id) ON DELETE CASCADE,
FOREIGN KEY (book_id) REFERENCES books (id) ON DELETE CASCADE
);
SELECT authors.author_name, COUNT(book_author_id.author_id) as count
FROM authors
LEFT JOIN book_author_id
ON book_author_id.author_id= authors.id
LEFT JOIN books
ON book_author_id.book_id= books.id
GROUP BY authors.author_name
HAVING COUNT(DISTINCT book_author_id.author_id) >= 3;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question