表作者:
id | name_author
---------
1 | david
2 | kate
3 | tom
4 | mark
表格书:
id | name_book
------------
1 | book1
2 | book2
3 | book3
表关系作者和书籍
id_book | id_author
-------------------
1 | 2
1 | 3
1 | 4
2 | 2
1 | 1
3 | 4
因此,我必须得到“Book1”这本书,因为它有4位作者(大卫,凯特,汤姆,马克)。
如何向mysql写一个查询?
答案 0 :(得分:1)
你可以写出类似的东西(未经测试)
select name_book
from books as b
, link_book_author as l
where b.id = l.id_book
group by name_book
having count(id_author) = 4
答案 1 :(得分:0)
简单如下:
SELECT COUNT(DISTINCT(id_author)) as authors_num,id_book
FROM table1
GROUP BY id_book
HAVING authors_num=4
如果您需要书名:
SELECT COUNT(DISTINCT(table1.id_author)) as authors_num,
table1.id_book,
books.name_book
FROM table1
LEFT JOIN books
ON books.id = table1.book_id
GROUP BY id_book
HAVING authors_num=4
答案 2 :(得分:0)
也许吧:
SELECT b.name_book, a.name_author
FROM relationships r
JOIN books b ON r.id_book = b.id
JOIN author a ON r.id_author = a.id
WHERE b.name_book = 'Book1'
;
结果:
+-----------+-------------+
| name_book | name_author |
+-----------+-------------+
| book1 | kate |
| book1 | tom |
| book1 | mark |
| book1 | david |
+-----------+-------------+
4 rows in set (0.00 sec)
或者:
SELECT b.name_book, GROUP_CONCAT(a.name_author) authors
FROM relationships r
JOIN books b ON r.id_book = b.id
JOIN author a ON r.id_author = a.id
WHERE b.name_book = 'Book1'
;
结果:
+-----------+---------------------+
| name_book | authors |
+-----------+---------------------+
| book1 | kate,tom,mark,david |
+-----------+---------------------+
1 row in set (0.00 sec)
答案 3 :(得分:0)
SELECT
b.name_book, GROUP_CONCAT(a.name_author) authors
FROM relationships r
JOIN books b ON r.id_book = b.id
JOIN author a ON r.id_author = a.id
GROUP BY r.id_book
HAVING COUNT(r.id_book) = 4
;