views:

207

answers:

2

Hi guys. The project I'm working on has two type of accounts, "people" and "companies". I hold a single "users" table with all the accounts and just the basic info needed for login (email, pass, etc), and two other tables "user_profiles" (regular people) and "company_profiles" (companies) that hold more specific columns for each type, both of the tables linked to the general "users" table via a "profile_user_id" column.

Now, the problem: whenever I want to list users that can be both people and companies, I use a: "select user_id, user_type, concat_ws('', concat_ws(' ', user_profiles.profile_first_name, user_profiles.profile_last_name), company_profiles.profile_company_name) as user_fullname ". When I list these users I know whether they're people or companies by the "user_type".

Is my approach using concat_ws the right (optimal) one? I did this instead of select-ing every *_name to avoid returning more columns than necessary.

Any protips are very welcome :).

Thanks

EDIT: the query above continues like: from users left join user_profiles on ... left join company_profiles on ...

+5  A: 

select u.user_id, u.user_type, concat_ws(profile_first_name + profile_last_name) as full_name from users u, user_profiles up where u.key = up.key and u.user_type = 'user'

union

select u.user_id, u.user_type, concat_ws(profile_first_name + profile_last_name) as full_name from users u, company_profiles cp where u.key = cp.key and u.user_type = 'company'

mson
Considering that the two `profile` tables have disjoint sets of `users`, because a user can be either a `person` or a `company`, is the UNION solution better than my initial concat idea?
idevelop
run an explain plan and see the differencerelational databases are meant for processing sets
mson
Both queries end up doing 2 joins. This one is more explicit and understandable, IMHO.
tvanfosson
+1  A: 

Does the query you already have work? Is it that you're experiencing performance issues from using this approach already?

Unless using the above query is taking way longer than you're expecting it to be or is causing issues in the software calling this information, this might be pre-mature optimization.

One thing to note though, your first use of CONCAT_WS doesn't have a seperator, so the company name is going to be merged with the person's name.

invenetix
The query I wrote above already works, I'm just questioning its optimality. The reason the first concat_ws doesn't have a separator is that I'm actually concating two columns one of which I *know* is NULL after left joining the users table to the user_profiles and company_profiles.
idevelop
So if you're not expecting to have both user_profile AND company_profile information present for a single user entry to do something like "Stephen Colbert, Comedy Central" then MSON's query would be best.
invenetix