我有两个表,books
和authors
。 books
有author_id
列和secondary_author_id
列(没有书籍超过两位作者)。我到目前为止:
SELECT * FROM books
LEFT JOIN authors
ON books.author_id=authors.id
正在处理与第一作者的联接。我无法理解我如何处理第二作者。我应该更改我的架构,还是只需要一点SQL帮助?
答案 0 :(得分:4)
SELECT books.*, author1.*, author2.*
FROM books
LEFT JOIN author AS author1
ON author1.author_id = books.author_id
LEFT JOIN author AS author2
ON author2.author_id = books.secondary_author_id
在SQL中,您可以通过在表名后添加表来为表添加别名。请注意,现在您将拥有重复的列,因此您可能希望为author1和author2的结果添加别名而不是author1。*。
修改强>
其他详细信息 - 假设您有基本表(我将包含详细信息,以便人们想要自己测试):
CREATE DATABASE test;
USE test;
CREATE TABLE books
(
book_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
author_id INT NOT NULL,
secondary_author_id INT
);
CREATE TABLE authors
(
author_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);
INSERT INTO authors (author_id,name) VALUES (1,'Sue Z. Que'),(2,'John Doe'),(3,'Bob Smith');
INSERT INTO books (book_id,title,author_id,secondary_author_id) VALUES (1,'JOIN-ing Two Tables',1,2);
如果您执行上面提到的选择,您的结果将如下:
|----------------------- books TABLE -----------------------------|---- authors table -----|---- authors table ---|
+---------+---------------------+-----------+---------------------+-----------+------------+-----------+----------+
| book_id | title | author_id | secondary_author_id | author_id | name | author_id | name |
+---------+---------------------+-----------+---------------------+-----------+------------+-----------+----------+
| 1 | JOIN-ing Two Tables | 1 | 2 | 1 | Sue Z. Que | 2 | John Doe |
+---------+---------------------+-----------+---------------------+-----------+------------+-----------+----------+
(我为了Calrity而添加了顶部标题)你看到你有两个author_id和两个名字(因为它们是同一个表和相同列名的连接)。但是,如果您对连接中的列进行别名,请执行以下操作:
SELECT books.*, author1.name AS primary_author, author2.name AS secondary_author
FROM books
LEFT JOIN authors AS author1
ON author1.author_id = books.author_id
LEFT JOIN authors AS author2
ON author2.author_id = books.secondary_author_id;
你得到了更清晰的结果:
|----------------------- books TABLE -----------------------------| authors table -|- authors table --|
+---------+---------------------+-----------+---------------------+----------------+------------------+
| book_id | title | author_id | secondary_author_id | primary_author | secondary_author |
+---------+---------------------+-----------+---------------------+----------------+------------------+
| 1 | JOIN-ing Two Tables | 1 | 2 | Sue Z. Que | John Doe |
+---------+---------------------+-----------+---------------------+----------------+------------------+
答案 1 :(得分:2)
SELECT books.* FROM books, authors.name, secondary_authors.name
LEFT JOIN authors
ON books.author_id=authors.id
LEFT JOIN authors as secondary_authors
ON books.secondary_author_id=secondary_authors.id
答案 2 :(得分:1)
你需要重新考虑你的设计,因为有一天会有一本书有三位作者,第二天会有一本零书。 (我自己去过那里。)
修改强>
正如您的评论所说:是的,您需要一个books_authors表。只要您正确设置了索引,就不会有很大的性能损失。
最烦人的部分是你经常想要将作者串在一起(每本书一个条目,将所有作者连成一列)。你可能最终会为此创建一个视图。
答案 3 :(得分:0)
只需在辅助ID上进行另一次加入