2017-06-07 22 views
1

我有这个数据库。创建了3个表格。SQL请求与计数

我需要查询数据库以提取其中有超过三位作者的标题。

我尝试过不同的方法,但是我无法计算三个或更多作者写的书的数量。我怎样计算我的桌子上有多少回音?

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

回答

1

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

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

+0

太谢谢你了 – Kris

+0

很高兴帮助你摆脱这个障碍。 –

+0

当然,由于使用'> ='而不是'>'这也会检索哪里有_exactly_三位作者。 –

1

你可以试试这个查询

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