This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes JDBC and the fly likes Is it possible to select across multiple rows into the same result? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Is it possible to select across multiple rows into the same result?" Watch "Is it possible to select across multiple rows into the same result?" New topic
Author

Is it possible to select across multiple rows into the same result?

Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
Hello,

I will need to be querying a database schema which models an object hierarchy tree, with a single table containing every parent-child relationship in the tree. So to find the TypeA children of a specific parent you'd do something like

SELECT * FROM TypeA, relationships WHERE relationships.parentid = <parentid> AND relationships.childid = TypeA.id

That's straightforward enough, but what if you're trying to find grandchildren? Or a single query involving multiple different types (tables) of children? That would mean that multiple rows of "relationships.childid" would be used for the same row in the result set. Is there any way to do this without using either multiple seperate queries or nested queries.

Changing the table design of the schema is not an option, unfortunately, though it is possible to add new tables and views.

Thank you,
Yuriy
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30138
    
150

Yuriy,
You can use the "union" operator to separate different numbers of joins. While the database still has to execute the parts of the query, it is only one database round trip. This only works if you know how many levels you can have though. It may be more efficient to do the separate queries.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
All right, thank you!

-Yuriy
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Is it possible to select across multiple rows into the same result?
 
Similar Threads
Passing a Statement instead of a Connection?
Storing a tree structure in a relational database..
Insights on database programming
Statements about JPQL
SQL -SELECT on multiple tables overhead