Ask the Expert

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: