I have a BOOK table that stores books, and a SIMI_BOOK table that stores the similarity values of any 2 books. Below are the keys used by the 2 tables.
BOOK: bid btitle
SIMI_BOOK: bid1 bid2 similarityI need a join query that could fetch all the information about the OTHER book.
For example, when a user visits a particular book page (bookA), it can fetch all the books in SIMI_BOOK with either bid1=bookA or bid2=boo开发者_JAVA技巧kA, then join bid2 or bid1 with BOOK respectively to fetch the info about the OTHER book.
Any ideas on how to achieve that?
Thank you in advance.You can try something similar to:
SELECT * (or what you need)
FROM SIMI_BOOK JOIN BOOK ON (BOOK.bid = SIMI_BOOK.bid1)
WHERE SIMI_BOOK.bid2 = nnn (your primary book id)
UNION
SELECT * (or what you need)
FROM SIMI_BOOK JOIN BOOK ON (BOOK.bid = SIMI_BOOK.bid2)
WHERE SIMI_BOOK.bid1 = nnn (your primary book id)
What about:
SELECT b2.*
FROM Book B2
JOIN Simi_Book SB ON SB.Bid2 = B2.Bid AND SB.Bid1 = ?
UNION
SELECT b1.*
FROM Book B1
JOIN Simi_Book SB ON SB.Bid1 = B1.Bid AND SB.Bid2 = ?
Only one of the two queries will return a value - unless you have rows with both (Bid1 = X, Bid2 = Y) and (Bid1 = Y, Bid2 = X) in the Simi_Book table. The '?' placeholder is the value of the book ID that you do have; the same value should be supplied twice.
You'll need LEFT JOIN and AS statements.
Do the following.
- fetch all books in SIMI_BOOK
- do a left join for bid1
- do another left join for bid2
Hope this helps.
精彩评论