[英]sql request with Count
I have this data base. 我有这个数据库。 Created 3 tables. 创建了3个表。
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. 下面提到的查询将帮助您提取3位以上作者的书名。
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 如果您对条件的计数超过3,那么您将获得总书数> = 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 如果您需要作者姓名,则可以对以下查询使用GROUP_CONCAT
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.