0

我有一个带有学生表的数据库。结构是这样的

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

但它给我一个错误

4

4 回答 4

0

与其修复您的查询,不如规范化关系表的数据borrowing

更改为保存数据的方式,例如:

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
于 2014-03-27T04:45:47.330 回答
0
id      students_id     books_id
---     ------------    ---------
1       1               1
2       1               3
3       2               2
3       3               3

select s.name, bk.title
from student s
inner join borrowing b
on s.id = b.students_id
inner join book bk
on b.book_id = bk.id
where s.id = 1
于 2014-03-27T04:45:55.267 回答
0

使用这个函数,在你的数据库中创建这个函数。

ALTER FUNCTION [dbo].[funcSplit]
(
    @param      NVARCHAR(MAX),
    @delimiter  CHAR(1)
)
RETURNS @t TABLE (val NVARCHAR(MAX))
--select * from dbo.funcSplit('1,3',',')
AS
BEGIN
    SET @param += @delimiter

    ;WITH a AS
    (
        SELECT CAST(1 AS BIGINT) f,
               CHARINDEX(@delimiter, @param) t,
               1 seq
        UNION ALL
        SELECT t + 1,
               CHARINDEX(@delimiter, @param, t + 1),
               seq + 1
        FROM   a
        WHERE  CHARINDEX(@delimiter, @param, t + 1) > 0
    )
    INSERT @t
    SELECT SUBSTRING(@param, f, t - f)         
    FROM   a
           OPTION(MAXRECURSION 0)

    RETURN
END

然后执行这段代码,

select s.sname,bk.bname,f.val from stud as s
left join  borrowing as b on s.sid = b.students_id
cross apply dbo.funcSplit(b.bookid,',') as f
left join books as bk on bk.bookid = f.val
where sid = 1
于 2014-03-27T04:46:06.283 回答
0

实际上你必须在查询中使用 group_concat()

前提是您应该有一个像@sotondolphin 在上面的答案中所说的表来使用以下查询

尝试这个

select user_id,group_concat(book_id) from userTable
inner join book_borrow_tbl on  userTable.user_id=book_borrow_tbl.user_id
group by user_id
于 2014-03-27T04:48:10.267 回答