0

I am having problems forming an sql query.

Table stucture:

 TABLE A:
 id     | data_a 
--------|--------
 1      | data1  
 2      | data2   
 3      | data3   

 TABLE B:
  id     | data_b | a_id 
 --------|--------|--------
  1      | data4  | 1
  2      | data5  | 1
  3      | data6  | 2
  4      | data7  | 3
  5      | data8  | 3

 TABLE C:
  id     | data_c | b_id   | x_id   
 --------|--------|--------|--------
  1      | data9  | 1      | 1
  2      | data10 | 2      | 1
  3      | data11 | 3      | 1
  4      | data12 | 1      | 2
  5      | data13 | 4      | 2 

Required output:

 data_a | data_b | data_c 
--------|--------|--------
 data1  | data4  | data12
 data1  | data5  | 
 data2  | data6  | 
 data3  | data7  | data13
 data3  | data8  | 

Current sql:

SELECT data_a, data_b, data_c
FROM a 
LEFT JOIN b ON a.id = b.a_id 
LEFT JOIN c ON b.id = c.b_id
WHERE c.x_id = 2 OR c.x_id = null;

SQL fiddle

5
  • Please add some explanation as to what you're trying to do. Commented Jan 6, 2017 at 6:30
  • @shmosel trying to get the required output Commented Jan 6, 2017 at 6:32
  • I generally upvote qustions with sql fiddles and downvote questions wth table a, table b, table c. why do you go out of your way to make things difficult? Commented Jan 6, 2017 at 6:33
  • @e4c5 I prefer fiddles to, didn't want to get told off for a required part of the question being hosted elsewhere. Commented Jan 6, 2017 at 6:36
  • I just explained why I didn't downvote your question for all your a,b,c stuff Commented Jan 6, 2017 at 6:37

2 Answers 2

5

Put the x_id = 2 in left join condition.

SELECT
  data_a, 
  data_b, 
  data_c

FROM
  a LEFT JOIN b ON a.id = b.a_id
    LEFT JOIN c ON b.id = c.b_id and c.x_id=2;
Sign up to request clarification or add additional context in comments.

Comments

1

Try this : -

SELECT
  data_a, 
  data_b, 
  data_c

FROM
  (Select data_a,data_b,b.id from a LEFT JOIN b ON a.id = b.a_id) as k
    LEFT JOIN (Select * from c WHERE
  c.x_id = 2 OR c.x_id = null) as j ON k.id = j.b_id

for exact match just add this :-

order by data_a,data_b

1 Comment

thanks for your help. This does work but wonderbell's answer does not require a nested select statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.