(flemming.madsen@gmail.com) writes:
[quoted text, click to view] > A table of users containing the fields always required for a user.
> users:
> userid
> email
> name
> password
> projectid
>
> A table of extra properties for a user that can be different from each
> project.
> These properties can be "location", "department", and so on.
> userproperties
> userpropertyid
> propertyname
> projectid
>
> A table of the value of each of the extra properties for each user
> userpropertyvalues
> userpropertyid
> userid
> userpropertyvalue
>
>
> Now I want to do a select statement that returns
>
> userid, email, name, password, propertyname[1], propertyname[2],
> propertyname[3]
>
>
[userid],[email],[name],[password],[propertyvalue1],[propertyvalue2],propert
yvalue[3]
[quoted text, click to view] >
> (when I pass a projectid)
>
> I just don't seem to be able to do that. Any ideas?
For this kind of questions, it always a good idea to include:
o CREATE TABLE statements for your tables.
o INSERT statements with sample data.
o The desired result given the sample.
This permits anyone who answer to post a tested query.
In you case, there are several loose ends. For instance, in the
userpropertyvaules, I would expect a projectid, since I would
expect (projectid, userpropertyid) to be the primary key of
userproperties. It seems now that userpropertyid alone is the
key. Another loose end is how you now which propertyvalue is #1
and so on. Furthermore, do we know if all users have all properties
for a project?
So this query is very much just a sketch, but hopefully you can work
from it.
SELECT u.userid, u.email, u.name, u.password, upv1.userpropertyvalue,
upv2.userpropertyvalue, upv3.userpropertyvalue
FROM users u
JOIN userproperties up1 ON u.projectid = up1.projectid
JOIN userproperties up2 ON u.projectid = up2.projectid
JOIN userproperties up2 ON u.projectid = up2.projectid
LEFT JOIN userpropertyvalues upv1
ON up1.userpropertyid = upv1.userpropertyíd
AND upv1.userid = u.userid
LEFT JOIN userpropertyvalues upv2
ON up2.userpropertyid = upv2.userpropertyíd
AND upv2.userid = u.userid
LEFT JOIN userpropertyvalues upv3
ON up3.userpropertyid = upv3.userpropertyíd
AND upv3.userid = u.userid
WHERE u.projectid = @projectid
AND up1.projectid = @projectid
AND up2.projectid = @projectid
AND up3.projectid = @projectid
--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server SP3 at