具有多个值的mysql查询

时间:2014-03-27 04:39:24

标签: mysql sql multiple-value

我有一个包含学生桌子的数据库。结构就像这样

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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