简体   繁体   中英

How to put condition based query for MySQL

I want to create a forum.

Scenario:
When a user click on question list from forum, It will redirect a page where he can find the respective Question and list of answer,

Whenever i used below mentioned query, I found the question from the question table ( im_forum_question ) on the new page.

'SELECT q.id, q.forum_question, q.forum_question_point
 FROM im_forum_question as q '+
 WHERE q.id='+"'"+req.params.id+"' "

But when i mix above code with answer fetching query below mentioned, I only get the already answered question. For an unanswered question it is showing an error.

'SELECT  q.id, q.forum_question, q.forum_question_point,  qa.forum_answer, qa.user_name_answer
 FROM im_forum_question as q
   INNER JOIN im_forum_question_answer as qa
      ON qa.question_id = q.id
 WHERE q.id='+"'"+req.params.id+"' "

Because if no one answered that question, it will not be stored in answer table ( im_forum_question_answer ).

  1. Is there any way if number 2 query (Above mentioned) failed the number 1 query (Above mentioned) will execute. (if, else)
  2. If no answer found form answer table only question should show.

     exports.get_question_answer = function(req, res, next){ db.sequelize.query( 'SELECT q.id, q.forum_question, q.forum_question_point, qa.forum_answer, qa.user_name_answer FROM im_forum_question as q '+ ' INNER JOIN im_forum_question_answer as qa ON qa.question_id = q.id '+ ' WHERE q.id='+"'"+req.params.id+"' " ).then(function(data){ console.log('Logs for Data', data); var arr = data[0]; res.render('forum/question.ejs',{ success:'', error:'', session: req.session.user, data:arr }) }) } 

After a quick look, I think that the reason why you don't get an answer is because you use an INNER JOIN . An inner join returns only the rows that are common in both tables so when the specific id is not found in the answers table the row is skipped entirely in the returned table (for a nice explanation of joins see here ).

To achieve what you want you should use a LEFT JOIN instead. This will return all the matched records from the left table (in this case your questions table). For the cases that no matching answer is found, the entries will be null.

The second thing that you could fix is that error you get. This is most probably due to the fact that you are returning

var arr = data[0];

However, in cases that the array is empty this will be undefined. This could lead to an error if you don't take this into account in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM