If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Creating a conditional query

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 08-13-04, 19:38
gcornish gcornish is offline
Registered User
 
Join Date: Aug 2004
Posts: 1
Creating a conditional query

Good Morning

I have the following situation: I have three tables; one for books, one for categories, and one to link the two. Every book must have at least one category, but may have more.

Now I'd like to do a search for books, sorted by their categories, except I'd like each book to only be returned once. In addition, I'd like to specify a category such that, if the book is in this category, this is the category returned; if not, any one of the book's categories may be returned.

In other words, if I have ten categories (ids 1 - 10), and I choose category 6, I'd like to write a query that will return two columns (bookid and categoryid). Every book will be represented once and only once in the result. All books in category 6 will return 6 in the categoryid column. Other books will return any one of the category ids to which the book belongs.

Does any of this make sense?

Let me explain further with an example:

Books table - 5 books (ids 1 - 5)
Categories table - 5 cats (ids i-5)
Links table:
bookid catid
1 2
1 4
1 5
2 4
3 5
4 1
4 3
5 2
5 4


The results I want are as follows (ordered by book, not category) (I selected catid 4 as significant)
bookid catid
1 4
2 4
3 5
4 1 (or 3)
5 4


Can anyone help me compose this query?

Cheers

G
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On