假设我有作者(id,name),Book(id,name),Book_Author(bookid,authorid),Book_Reader表(bookId,authorId)表。
AUthor(id, name) ======== 1 | James 2 | Ivan 3 |John 4 |Harry Book(id, name) ============= 1 | Introducing Mysql 2 | Hibernate tutorials Book_Author(bookId, authorId) ========= 1 | 1 2 | 3 Book_reader(bookId, authorId) ============= 1 | 1 1 | 3 1 | 4
其中bookAuthor表代表书的作者,书籍读者代表作者阅读该书。
现在,我希望查询将返回我的书,书的作者和作者列表阅读该书。
Bookname Author Readers ================================================ Introducing Mysql James James,John,Harry
或者我想要所有的作者是詹姆斯或读者的书是詹姆斯。 谢谢,
答案 0 :(得分:0)
select
b.name,
a1.name as author,
group_concat(a2.name) as reader
from
book_reader br
inner join book b on b.id = br.bookId
inner join book_Author ba on ba.bookId = br.bookId
inner join author a1 on a1.id = ba.authorId
inner join author a2 on a2.id = br.authorId
group by b.id
<强> DEMO 强>
我想要詹姆斯是作家或詹姆斯是读者的所有书籍
对于上述情况,您可以使用where where condition
select
name,
type
from
(
select
b.name,
'Author' as type
from book b
inner join book_author ba on ba.bookId = b.id
inner join author a on a.id = ba.authorId
where a.name = 'James'
UNION ALL
select
b.name,
'Reader' as Type
from book b
inner join book_reader br on br.bookId = b.id
inner join author a on a.id = br.authorId
where a.name = 'James'
)t
<强> DEMO 强>
我添加了UNION ALL
以列出所有内容并输入列作为通知阅读或作者的列。如果你不想那只是删除,也可以只使用UNION
以防万一你不想要重复的书名。
答案 1 :(得分:0)
书籍,作者和读者:
SELECT b.name AS BookName, a1.name AS AuthorName, group_concat(DISTINCT a2.name) AS readers
FROM book_reader AS br
JOIN book AS b on b.id = br.book_id
JOIN book_author AS ba on ba.book_id = br.book_id
JOIN author AS a1 on a1.id = ba.author_id
JOIN author AS a2 on a2.id = br.author_id
GROUP BY b.id;
我在此查询中使用了表别名来减少输入的数量。 GROUP_CONCAT()
函数用于将读者名称组合成一列。
作者是詹姆斯的书:
SELECT book.name
FROM book_author
JOIN book ON book.id = book_author.book_id
JOIN author ON author.id = book_author.author_id
WHERE author.name = "James";
读者是詹姆斯的书:
SELECT book.name
FROM book_reader
JOIN book ON book.id = book_reader.book_id
JOIN author ON author.id = book_reader.author_id
WHERE author.name = "James";