我有作业,必须从两个表(书和作者)中选择数据。图书有两位作者,我需要显示结果并以书名和作者之间用逗号分隔。
我自己尝试过,但遇到错误。
模式SQL:
CREATE TABLE IF NOT EXISTS `author` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(128),
`surname` VARCHAR(128),
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8mb4 ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `book` (
`id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(128),
`author_id` INT NOT NULL,
`author_id_2` INT NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8mb4 ENGINE=InnoDB;
查询SQL:
INSERT INTO `author` (`name`, `surname`) VALUES ("William", "Shakespeare");
INSERT INTO `author` (`name`, `surname`) VALUES ("Agatha", "Christie");
INSERT INTO `author` (`name`, `surname`) VALUES ("J. K", "Rowling");
INSERT INTO `author` (`name`, `surname`) VALUES ("George", "Orwell");
INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("Hamlet", 1, 2);
INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("Macbeth", 1, 3);
INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("Murder on the Orient Express", 2, 3);
INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("The Secret of Chimneys", 2, 1);
INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("1984", 3, 1);
INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("Animal Farm", 3, 2);
查询:
SELECT
b.title Pavadinimas,
concat(concat(a1.name, ' ', a1.surname), ', ', concat(a2.name, ' ', a2.surname) Autoriai
FROM book b
INNER JOIN author a1 WHERE book.author_id=a1.id
INNER JOIN author a2 WHERE book.author_id_2=a2.id;
结果应为:
Hamlet | William Shakespeare, Agatha Christie
答案 0 :(得分:0)
您需要将book表与author表连接两次,例如:
SELECT
b.title,
CONCAT(a1.name, ' ', a1.surname, ', ', a2.name, ' ', a2.surname) authors
FROM book b
INNER JOIN author a1 ON b.author_id = a1.id
INNER JOIN author a2 ON b.author_id_2 = a2.id
此 demo on DB Fiddle 及其示例数据将返回:
| title | authors |
| ---------------------------- | ------------------------------------ |
| Hamlet | William Shakespeare, Agatha Christie |
| Macbeth | William Shakespeare, J. K Rowling |
| Murder on the Orient Express | Agatha Christie, J. K Rowling |
| The Secret of Chimneys | Agatha Christie, William Shakespeare |
| 1984 | J. K Rowling, William Shakespeare |
| Animal Farm | J. K Rowling, Agatha Christie |
注意:如果您的书籍只有一位作者,则可以使用LEFT JOIN
代替INNER JOIN
。