Q
Problem solve Get help with specific problems with your technologies, process and projects.

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


Dig Deeper on Oracle and SQL

SearchDataManagement
SearchBusinessAnalytics
SearchSAP
SearchSQLServer
TheServerSide.com
SearchDataCenter
SearchContentManagement
SearchHRSoftware
Close