简体   繁体   中英

sql request with Count

I have this data base. Created 3 tables.

I need to query the database to extract the titles in which more than three authors.

I tried different ways, but I can not count the number of books written by three or more authors. How can I calculate how many echoes wrote the book in my table?

 CREATE TABLE `authors` (
      `id` int(11) NOT NULL,
      `name` text CHARACTER SET utf8 NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `authors` (`id`, `name`) VALUES
(1, 'Orwell'),
(2, 'Balsak'),
(3, 'Gugo');

-- --------------------------------------------------------

CREATE TABLE `books` (
  `id` int(11) NOT NULL,
  `title` text CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `books` (`id`, `title`) VALUES
(1, '1984'),
(2, 'crime and punishment'),
(3, 'Hunger games');

-- --------------------------------------------------------

CREATE TABLE `books_authos` (
  `author_id` int(11) DEFAULT NULL,
  `book_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books_authos` (`author_id`, `book_id`) VALUES
(1, 1),
(1, 3),
(1, 2),
(3, 2),
(2, 2);

Below mentioned query will help you to extract title of book written by more than 3 authors.

SELECT b.title AS titles FROM books b
INNER JOIN books_authos ba ON ba.book_id = b.id
GROUP BY ba.book_id
HAVING COUNT(DISTINCT(ba.author_id)) >= 3

Let me know if you need other specific output.

You can try this query

SELECT count(books_authos.author_id) AS total_author, books.title FROM books_authos INNER JOIN books ON books.id = books_authos.book_id group by book_id

Out put

total_author   title
1              1984
3              crime and punishment
1              Hunger games

If you put condition on count for more than 3 then you will get book which has total >= 3

SELECT count(books_authos.author_id) AS total_author, books.title FROM books_authos INNER JOIN books ON books.id = books_authos.book_id group by book_id having total_author >= 3

Output

 total_author   title
3              crime and punishment

If you need authors name then you can try this one

If you want author name then you can use GROUP_CONCAT with below query

SELECT b.*, COUNT(ba.author_id) AS total_author, GROUP_CONCAT(au.name) AS authors_name FROM books b 
LEFT JOIN books_authos ba ON b.id = ba.book_id
LEFT JOIN authors au ON au.id = ba.author_id
GROUP BY b.id

Output

total_author   title                    authors_name
 1               1984                   Orwell
 3              crime and punishment   Gugo, Balsak,Orwell    
 1              Hunger games           Orwell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM