I have a User table. Among others, it has these 4 columns:
------ UserID
------- | ---- Username
----- | --- CreatedBy
--- | ParentUserID
(PK, bigint, not null) | (char(20), not null) | (varchar(50), null) | (bigint, null)
Both ParentUserID and CreatedBy points at the "owner account", by the UserID or Username respectively. Both are unique.
CreatedBy is never actually null
, but UserID is indexed, so ParentUserID is preferred - and it's also the one we're moving towards.
Obviously I'm not fluent in SQL, but this is my idea of it:
SELECT Users.*
FROM tblUsers AS Owners
LEFT JOIN tblUsers AS Users
ON
ISNULL(Users.ParentUserID = Owners.UserID,
Users.CreatedBy = Owners.Username)
WHERE Owners.UserID = 14;
This is as far as I've gotten:
SELECT ISNULL(POwners.UserID, COwners.UserID) AS OwnerID, Users.*
FROM tblUsers AS Users
RIGHT JOIN tblUsers AS POwners ON Users.ParentUserID = POwners.UserID
RIGHT JOIN tblUsers AS COwners ON Users.CreatedBy = COwners.Username
WHERE OwnerID = 14;
Although obviously this doesn't work. On a secondary note, I further need to convert this to LINQ, but for this question, it is only relevant so far that the query will be possible to convert, which I would expect of the vast majority of queries.