One query to return disjoint sets (MySQL)

I have three tables: parts, components and operations. I have a part with six components and five operations, but my recordset contains thirty records when I use LEFT JOINs. Can I construct one query to return just the 11 records I want? I'm using MySQL.

    Requires Free Membership to View

Use UNION instead of LEFT JOIN. (UNION is implemented in MySQL 4.0.0.)

select P.partno
     , CONCAT('Component: ', C.componentname) 
  from parts P
inner 
  join components C
    on P.partno = C.partno
union all
select P.partno
     , CONCAT('Operation: ', O.operationname) 
  from parts P
inner 
  join operations O
    on P.partno = O.partno

Note it's UNION ALL because there can be no duplicates across the two subqueries.

If you're not on MySQL 4.0.0, there is another way, a rather clever way, which I have not tested myself, although I expect it should work quite well. See the article Writing UNION statements in MySQL 3.x.

For More Information


This was first published in January 2003

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.