簡體   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