我目前停留在我试图整理的SQL查询中。
这是表格布局:
<小时/>
tblUsers 此表包含更多列,但在示例中不是必需的
示例数据:
------
| ID |
------
| 1 |
------
| 2 |
------
tblColumns
示例数据:
--------------------
| ID | Column Name |
--------------------
| 1 | Name |
--------------------
| 2 | Email |
--------------------
| 3 | Age |
--------------------
tblColumnData
示例数据:
----------------------------------------------
| ID | UserID | ColumnID | ColumnDataContent |
----------------------------------------------
| 1 | 1 | 1 | John Smith |
----------------------------------------------
| 2 | 1 | 2 | john@email.com |
----------------------------------------------
| 3 | 1 | 3 | 45 |
----------------------------------------------
| 4 | 2 | 2 | james@email.com |
----------------------------------------------
| 5 | 2 | 3 | 30 |
----------------------------------------------
因此,您将在上面看到,UserID:2在TIDlColumnData表中没有ColumnID 1(NAME列)的记录。即使它是NULL,我仍然需要在结果中出现。
所以我试图让数据像这样返回:
------------------------------------------------------
| UserID | ColumnID | ColumnName | ColumnDataContent |
------------------------------------------------------
| 1 | 1 | Name | John Smith |
------------------------------------------------------
| 1 | 2 | Email | john@email.com |
------------------------------------------------------
| 1 | 3 | Age | 45 |
------------------------------------------------------
| 2 | 1 | Name | NULL or '' |
------------------------------------------------------
| 2 | 2 | Email | james@email.com |
------------------------------------------------------
| 2 | 3 | Age | 30 |
------------------------------------------------------
我的选择看起来像这样:
SELECT cd.UserID,c.ColumnID,c.ColumnName,cd.ColumnDataContent
FROM tblColumns c
INNER JOIN tblColumnData cd ON c.ColumnID=cd.ColumnID
我尝试过INNER,OUTER,LEFT ....等所有不同的联接,但没有成功。
希望有人可以提供帮助:)
由于
答案 0 :(得分:2)
我认为这会对你有所帮助:
with userCTE as (
select
u.userId ,
c.columnId
from tblUsers as u
cross join tblColumns as c
)
select
u.* ,
Coalesce(cd.ColumnDatacontent, 'N/A') AS columnDataContent
from userCTE as u
left join tblColumnData as cd
on u.columnId = cd.columnId and u.userID = cd.userId
您还需要选择哪些列对您感兴趣,这只是一般示例如何获取所有需要的行。
如果需要,您可以使用COALESCE
或ISNULL
函数将NULL值转换为更具体的字符串。
答案 1 :(得分:1)
随着小提琴向下,我们都会失明,但如果它出现的话,这就是我先尝试的。
SELECT tblUsers.UserID,
tblColumns.ColumnID,
tblColumns.ColumnName
tblColumnData.ColumnDataContent
FROM tblUsers,
tblColumns
LEFT JOIN tblColumnData ON tblColumnData.ColumnID = tblColumns.ColumnID
AND tblColumnData.UserID = tblUsers.UserID
;
您希望用户和列的Cartesian Product左侧加入ColumnID上的数据表。
答案 2 :(得分:1)
我认为你需要使用CROSS JOIN。我没有测试过这个,但它有点像这样:
SELECT
d.UserId
,d.ColumnId
,d.ColumnName
,d.ColumnDataContent
FROM tblColumns c
CROSS JOIN tblusers u
LEFT join tblcolumndata d on d.columnid = c.columnid and d.userid = u.userid
答案 3 :(得分:0)
select CD.UserID,CD.ColumnID,t.ColumnName,CD.ColumnDataContent
from (select distinct u.UserID,c.ID,c.[ColumnName] tblUsers u
cross join tblColumns c)t
left join tblColumnData CD on t.UserID=CD.UserID,t.ColumnID=CD.ColumnID