Q

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.

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

Dig Deeper

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

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:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close