jgallagher has asked for the wisdom of the Perl Monks concerning the following question:
I hesitated posting this question, because it actually seems to be two poor questions. First, is there any way to use a combined query (PostgreSQL docs) through DBIx::Class? I've looked through SQL::Abstract and the DBIx cookbook to no avail. At first attempt, I can't even use search_literal because the string is stuffed into a WHERE clause:
becomes something like$schema->resultset('foo')->search_literal('EXCEPT SELECT * FROM bar')
which obviously isn't right (or even valid SQL).SELECT * FROM foo WHERE ( EXCEPT SELECT * FROM BAR )
The alternate/base question is really more SQL than Perl, but I'll go ahead and describe it anyway; I'm sure someone here has done something like this before.
Suppose I have two tables (say containers and items, with just ID columns) with a many-to-many mapping table (mapping, with two columns: container_id and item_id). Any given container can hold zero or more items, and any given item can be contained in zero or more containers. Finding out what items are in a given container (say '1') is easy:
or the roughly equivalent SQL$schema->resultset('items')->search({'mapping.container_id' => 1}, {jo +in => 'mapping'});
SELECT * FROM items LEFT JOIN mapping ON (items.item_id = mapping.item +_id) WHERE mapping.container_id = 1
However, the "inverse" query is not as obvious. How do I get a list of all items that are not in a given container? Simply modifying the above to say "container id != 1" doesn't work since an item could be in both container 1 and container 2. The following SQL will do it:
but that feels wasteful, with the added complication of translating it into DBIx::Class. Anyone have any suggestions? (Obviously the above tables are somewhat contrived; I tried to give enough information, but let me know if I need to elaborate some point.)SELECT items.item_id FROM items LEFT JOIN mapping ON (items.item_id = +mapping.item_id) EXCEPT SELECT items.item_id FROM items LEFT JOIN mapping ON (items.i +tem_id = mapping.item_id) WHERE mapping.container_id = 1
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Combined SQL Queries (e.g., EXCEPT) and DBIx::Class
by Ieronim (Friar) on Jul 26, 2006 at 21:54 UTC | |
by jgallagher (Pilgrim) on Jul 26, 2006 at 22:08 UTC | |
by Ieronim (Friar) on Jul 26, 2006 at 22:32 UTC | |
|
Re: Combined SQL Queries (e.g., EXCEPT) and DBIx::Class
by dirving (Friar) on Jul 26, 2006 at 20:38 UTC | |
|
Re: Combined SQL Queries (e.g., EXCEPT) and DBIx::Class
by davidrw (Prior) on Jul 26, 2006 at 20:52 UTC | |
|
Re: Combined SQL Queries (e.g., EXCEPT) and DBIx::Class
by Khen1950fx (Canon) on Jul 26, 2006 at 21:19 UTC |