views:

37

answers:

1

Using a site like StackOverflow as an example:

I have a table of users, questions, and user-questions mappings. My user-questions mappings table looks like this:

userID (int 8)
questionID (int 8)

When displaying a list of popular questions, I am trying to mark the questions that have been posed by the logged-in user. Is it more efficient to check if the user-question mapping exists for each question, or get all the user-question mappings for the logged-in user from the database once, and do the checking on the server-side?

Here is a visual example of the output I want to see:

Question 1: What? (you asked this)
Question 2: Who?
Question 3: Why? (you asked this)

+3  A: 

The presentation should always be left to the presentation layer. The logic for the presentation based on the business rules you've mentioned is faster if constructed in the database:

SELECT q.title,
       CASE 
         WHEN uq.who_asked = @user_id THEN 1 
         ELSE 0 
       END AS isYourQuestion
  FROM QUESTIONS q
  JOIN USER_QUESTIONS uq ON uq.question_id = q.question_id

Then, you can use the isYourQuestion to flag the application to display "(you asked this)" if the value is 1.

OMG Ponies
Plus one because it's a good idea. Then again, it's a whole different story if the user-question mapping is in a different table
Michael Clerx
@Michael Clerx: Meh, just a JOIN if that's the case.
OMG Ponies
Thanks for your answer! However, the user-question mappings are in a different table, so how would I do this then?
Chetan
@Chetan: Updated
OMG Ponies
@OMG Ponies: Fair enough :)
Michael Clerx