繁体   English   中英

带有计数的SQL请求

[英]sql request with Count

我有这个数据库。 创建了3个表。

我需要查询数据库以提取其中三个以上作者的标题。

我尝试了不同的方法,但是我无法计算三位或更多作者撰写的书籍数量。 如何计算表中有多少回声写了这本书?

 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);

下面提到的查询将帮助您提取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

让我知道您是否需要其他特定输出。

您可以尝试此查询

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

放出

total_author   title
1              1984
3              crime and punishment
1              Hunger games

如果您对条件的计数超过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

产量

 total_author   title
3              crime and punishment

如果您需要作者的名字,那么可以尝试这个

如果您需要作者姓名,则可以对以下查询使用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

产量

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.

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