Seyhan
Seyhan

Reputation: 69

Select result from table for matching 2 rows in mysql

I have a MySQL table has these fields

 ID, CID, QUESTION, ANSWER, USER

ID is auto increment, every record in table has ID;
CID is point to ID for ANSWER records

For example, we have 4 records, 2 of question 2 of answer, and Mike answers 2 questions

ID  CID  QUESTION  ANSWER         USER
1    0   Test      NULL           John
2    1   NULL      This is Test   Mike    
3    0   Example   NULL           Tracy
4    3   NULL      Yes it is      Mike

I want to list questions of which is Mike's answers. How can I match ID and CID fields in same table and print QUESTION for output

Upvotes: 0

Views: 179

Answers (2)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79929

I want to list questions of which is Mike's answers.

SELECT t1.*
FROM TableName t1
LEFT JOIN TableName t2 ON t1.ID = t2.CID
WHERE t2.Answer IS NOT NULL
  AND t2.User = 'Mike';

SQL fiddle Demo

Note that this gives you the list of questions that Mike has answered therefore you won't find mike listed on them:

ID CID     QUESTION         ANSWER  USER
1   0        Test             NULL   John
3   0       Example           NULL   Tracy

Upvotes: 4

AnandPhadke
AnandPhadke

Reputation: 13496

select QUESTION from yourtable 
where ID in(select ID from yourtable where User = 'Mike' and answer is NOT NULL)

Upvotes: 0

Related Questions