How to do a junction table referencing constraint? I want to create a questionnaire which matches some questions together.
CREATE TABLE questionnaire(
 question_id int  PRIMARY KEY
 question_name varchar
 question type int
 -- some other columns
)
CREATE TABLE mapping(
 question_id_type1 int
 question_id_type2 int
 CONSTRAINT fk_qid_type1
  FOREIGN KEY (question_id_type1)
  REFERENCES questionnaire(question_id)
 CONSTRAINT fk_qid_type2
  FOREIGN KEY (question_id_type2)
  REFERENCES questionnaire(question_id)
)

How do I enforce that question_id_type1 only has values in questionnaire that has a question_type = 1 and question_id_type2 only has values in questionnaire that has a question_type = 2.
I know that creating two tables to replace questionnaire i.e.
CREATE TABLE questionnaire_type1(...)
CREATE TABLE questionnaire_type2(...)

would solve the problem however i have some other columns/referencing keys in questionnaire that would be repeated in both tables. May i know what is the best way to solve this problem?
In questionnaire, add a key that includes the ID and the type so that it can be referenced.
CREATE TABLE questionnaire
             (question_id integer,
              question_type integer,
              ...
              PRIMARY KEY (question_id),
              UNIQUE (question_id,
                      question_type));

In mapping add columns for the types. Use check constraints to enforce they are 1 or 2 respectively. In the foreign key constraints, let the pair of ID and type reference the additional key of questionnaire.
CREATE TABLE mapping
             (question_id_type1 integer,
              question_type_type1 integer
                                  DEFAULT 1,
              question_id_type2 integer,
              question_type_type2 integer
                                  DEFAULT 2,
              ...
              CHECK (question_type_type1 = 1),
              CHECK (question_type_type2 = 2),
              FOREIGN KEY (question_id_type1
                           question_type_type1)
                          REFERENCES questionnaire
                                     (question_id,
                                      question_type),
              FOREIGN KEY (question_id_type2
                           question_type_type2)
                          REFERENCES questionnaire
                                     (question_id,
                                      question_type));