D
D
denislysenko2020-09-02 16:37:58
SQL
denislysenko, 2020-09-02 16:37:58

How to write 3 SQL queries (pure, not checks in the code)?

There are two tables:

CREATE TABLE `books` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`author_id` INT(11) NOT NULL,
`title` VARCHAR(255) NOT NULL,
`price` FLOAT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_author_id` (`author_id`),
CONSTRAINT `fk_author_id` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)

CREATE TABLE `authors` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
)


It is required to write 3 SQL queries (pure, not by checks in the code):

1. Display all books and their authors.
2. Find authors who don't have any books.
3. Find authors who have more than one book.

I only know basic SQL stuff. Can anyone explain on the fingers what needs to be done to solve this and what topics of the documentation need to be studied for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2020-09-02
@denislysenko

select `authors`.`name`, `books`.`title`
  from `books`
  left join `authors` ON `authors`.`id` = `books`.`author_id`

select `authors`.`name`, count(`books`.`id`) as cnt
  from `books`, `authors`
  group by `books`.`author_id`
  having count(`books`.`id`) = 0

select `authors`.`name`, count(`books`.`id`) as cnt
  from `books`, `authors`
  group by `books`.`author_id`
  having count(`books`.`id`) > 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question