Reputation: 1730
I am using Postgres and have the (working) SQL as something like:
SELECT
distinct(users.id),
users.*
FROM
public.addons,
public.containers,
public.users
WHERE
( (addons."value" = 'Something' AND addons."name" = 'bob') OR
addons."value" = 'Something else' AND addons."name" = 'bill') AND
(containers.id = addons.site_id AND
users.id = containers.user_id)
What I want to do is format this so that it returns a set of user objects. I am not sure how I format this so that its something like (not working):
@users = User.find(:include => [:users, :containers, :addons], :conditions => {( (addons."value" = 'Something' AND addons."name" = 'bob') OR
addons."value" = 'Something else' AND addons."name" = 'bill') AND
(containers.id = addons.site_id AND
users.id = containers.user_id) } )
Is this even possible?
Upvotes: 1
Views: 376
Reputation: 562328
First, you should understand that DISTINCT is not a function, it's a query modifier. The parentheses don't change that. DISTINCT means if there are any rows where every column returned are identical, reduce the duplicates to a single row. You can't reduce to a single row per distinct value in a single column (that's the job of GROUP BY).
Second, SQL result sets properly have one value per row per column. You could do some kind of aggregated string-concatenation like MySQL's GROUP_CONCAT, or an equivalent aggregate function in PostgreSQL, but then you've got a string mashing together all the values, which you then have to explode in Ruby code after fetching it.
So if you have multiple rows to fetch for a given users.id
just let them come back to the app in multiple rows. Then do some post-processing of the data in your application. Loop over fetching the rows, and add the attributes to a Ruby object one by one. If you're fetchiing data for multiple user id's in a given query, stuff the attributes into a hash of your user objects, keyed by user id. That way you don't need to fetch the rows in any particular order.
Third, I'm inferring from your "name" and "value" columns that you're using the Entity-Attribute-Value design, where users have multiple attributes, one per row. This is a design that subverts traditional relational data access, so you do end up having to write application code to preprocess and postprocess the data. If you could put each attribute into its own conventional column, which would be the relational way of storing data, your SQL queries would be a lot simpler.
Upvotes: 2