0

I have two tables: MAINCOLOR and SUBCOLOR with the data as:

MAINCOLOR :
MAINID COLOR
1 RED
2 BLUE
3 GREEN
SUBCOLOR:
SUBID MAINID SUBCOLOR STATUS
1 1 PINK 0
2 1 ORANGE 1
3 2 VIOLET 1

I need a result set as:

MAINID COLOR SUBCOLOR
1 RED ORANGE
2 BLUE VIOLET
3 GREEN

Resultset should be a join of MAINCOLOR and SUBCOLOR using MAINID. Need child data having status as 1.

Taryn
9,7465 gold badges49 silver badges74 bronze badges
asked Mar 11, 2013 at 10:54

1 Answer 1

3

You can get the result by using a LEFT JOIN between the maincolor and the subcolor.

The key is placing the filter of status=1 on the JOIN condition. Your code will be:

select m.mainid,
 m.color,
 s.subcolor
from maincolor m
left join subcolor s
 on m.mainid = s.mainid
 and s.status = 1

See SQL Fiddle with Demo.

The LEFT JOIN will return all rows from the maincolor table and any matching rows in the subcolor table. Since you what to apply a WHERE to the data in the subcolor table, then you will want to move that filter to the JOIN condition to get the result.

answered Mar 11, 2013 at 11:13
1
  • Hurray. It worked. I was trying with a where clause, not resulting the required result. Thanks bluefeet. Commented Mar 11, 2013 at 11:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.