Jump to content


Photo

Join Multiple table


Best Answer Barand, 19 August 2016 - 08:47 AM

I'd make a couple of changes

 

  1. move the WHERE condition to the JOIN condition for the answer table
  2. use a LEFT join for the txtanswer table
SELECT question.*, question_options.*, answer.*,txtanswer.*
FROM question
    LEFT JOIN question_options
        ON question.question_id = question_options.question_id
    LEFT JOIN answer
        ON answer.option_id = question_options.qtn_option_id
           AND answer.empid = 'EMP8969' 
	 LEFT JOIN txtanswer
		ON txtanswer.qtn_option_id= question_options.qtn_option_id
		 

And don't use *s in the SELECT, specify the required fields.

Go to the full post


  • Please log in to reply
2 replies to this topic

#1 FooKelvin

FooKelvin
  • Members
  • PipPipPip
  • Advanced Member
  • 140 posts

Posted 19 August 2016 - 01:09 AM

Hi Guys, i have a problem regarding on joining multiple tables, i was trying up for few days, but still can't get it done. This database is to join employee survey question regarding to one of the cafe. 

 

Below are my current non-working query.

SELECT question.*, question_options.*, answer.*,txtanswer.*
FROM question
    LEFT JOIN question_options
        ON question.question_id = question_options.question_id
    LEFT JOIN answer
        ON answer.option_id = question_options.qtn_option_id
	 JOIN txtanswer
		ON txtanswer.qtn_option_id= question_options.qtn_option_id
		WHERE answer.empid = 'EMP8969' 

This query show no result when i join to the txtanswer table.

Please download the attachment to view my table data. 

 

Thanks for your help.

Attached Files



#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 17,594 posts

Posted 19 August 2016 - 08:47 AM   Best Answer

I'd make a couple of changes

 

  1. move the WHERE condition to the JOIN condition for the answer table
  2. use a LEFT join for the txtanswer table
SELECT question.*, question_options.*, answer.*,txtanswer.*
FROM question
    LEFT JOIN question_options
        ON question.question_id = question_options.question_id
    LEFT JOIN answer
        ON answer.option_id = question_options.qtn_option_id
           AND answer.empid = 'EMP8969' 
	 LEFT JOIN txtanswer
		ON txtanswer.qtn_option_id= question_options.qtn_option_id
		 

And don't use *s in the SELECT, specify the required fields.


If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 FooKelvin

FooKelvin
  • Members
  • PipPipPip
  • Advanced Member
  • 140 posts

Posted 22 August 2016 - 05:29 AM

Thanks Barand!






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users