我有四个表:Books
,Magazine
,Member
和Transaction
,每个表都有Title
列。
图书表
BookId, Title, author, edition, no_of_books
1, Harry Potter, Jk rowling, 5, 11
杂志表:
MagazineId, Title, Publisher, edition, no_of_magazine
1, filmfare, bollywood, 5, 8
会员表:
MemberId, name, address, contact, email
4, Arjun, NO 56 park street, 071487845, arjun56@gmail.com
8, khan, no 21 new lane pune, 07487547, khan@gmail.com
当成员借用Book
或Magazine
时,Transaction
表会保留记录(Trans_item_id
为BookId
或MagazineId
)
例如:
交易表:
Trans_Id, Trans_Mem_Id, Trans_item_Id, Issue_date, Receive_date,Category
1, 4, 1,06-04-2016, 10-04-2016,book
2, 8, 1,08-04-2016, 11-04-2016,magazine
那么如何使用SQL从数据库中选择数据并向此显示顺序
例如:
Tran_id, Title, member name, issue date, receive date
谢谢。
答案 0 :(得分:0)
试试这个:
SELECT t.tran_id,
case when t.category = 'books' then b.title else t.title end AS title,
u.name,
t.issue_date,
t.receive_date
FROM transaction t
INNER JOIN member u
ON t.trans_mem_id = u.memberid
LEFT JOIN books b
ON t.trans_item_id = b.bookid
AND t.category = 'books'
LEFT JOIN magazines m
ON t.trans_item_id = m.magazineid
AND t.category = 'magazines'
答案 1 :(得分:0)
选择 t.trans_item_id为tran_id, 合并(b.title,ma.title), m.name,t.issue_date,t.receive_date 从 交易 内部联接 成员m在m.memberid = t.trans_mem_id上 离开加入 b上的书籍t.trans_item_id = b.bookid 离开加入 杂志ma t.trans_item_id = ma.Magazineid
答案 2 :(得分:0)
您需要再添加一个列,以确定借用的项目是书籍/杂志......
Select
t.Tran_ID,
case
when t.type = 'book'
then
(select title from book where book.I'd = t.transitemid)
else
(select title from magazine where magazineid = t.tranitemid) 'title',
m.member name, t.receivedate
from
transaction t, membertable m
where
t.Tranmemberid = m.memberid