我有一个数据库,其中有一个学生表。结构是这样的
id name
--- -----
1 Tini
2 Eka
然后是书籍表
id title
--- ------
1 Cinderella's story
2 Pinochio
3 Mickey Mouse
然后借用
id students_id books_id
--- ------------ ---------
1 1 1,3
2 2 2,3
我如何得到“蒂尼正在借用灰姑娘的故事和米老鼠”? 我已经尝试过这样的查询
select students.*, books.* , borrowing.*
(select books.title from borrowing
join books on books.id = borrowing.books_id
where books_.id = borrowing.books_id limit 1) as books_title
from borrowing
join students on students.id = borrowing.students_id
join books on books.id = borrowing.books_id
GROUP BY books.title
但是它给了我一个错误
最佳答案
与其修复查询,不如规范化关系表借用
的数据。
更改保存数据的方式,例如:
id students_id books_id
--- ------------ ---------
1 1 1
2 1 3
3 2 2
4 2 3
并且 id
列也不是必需的,您可以省略它。
然后获取每个学生的借阅列表就很简单了:
SELECT t1.name, GROUP_CONCAT(t3.title) AS borrowed_books
FROM students t1
LEFT JOIN borrowing t2 ON t2.students_id = t1.id
LEFT JOIN books t3 ON t3.id = t2.books_id
GROUP BY t1.name
关于mysql 查询多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678432/