2014-03-27 44 views
0

我有一個數據庫與學生的表。該結構是這樣的與多個值的MySQL查詢

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 

但它引發我一個錯誤

回答

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 
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 
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 
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