1

我有3张桌子如下:

Table 1: FormFields (FieldID, FormID, Title, DateModified, ...)
Table 2: ReportItems (ReportItemID, ReportID, FormID, Title, DateModified, ...)
Table 3: FormValues (ValueID, FormID, FieldID, Value, UserName, DateModified, ...)

例如,我选择了 FormFields 的 2 个字段作为我的 ReportItems。这两个字段是一对问答。每个问题可以有 1 个答案,也可以为 NULL。关键是结果应该是这样一个带有'dt's和'dd's的html数据列表(dl),如下所示:

ReportID    FormID  FieldID Value (Question1)   UserName
ReportID    FormID  FieldID Value (Answer1)     UserName
ReportID    FormID  FieldID Value (Question2)   UserName
ReportID    FormID  FieldID Value (Answer2)     UserName
ReportID    FormID  FieldID Value (Question3)   UserName
ReportID    FormID  FieldID Value (Answer3)     UserName

Question 1
    Answer 1
Question 2

Question 3
    Answer 3
Question 4

Question 5
    Answer 5

我使用了这样的查询,但它没有返回我希望的结果:

select rf.FormID, rf.FieldID, rf.ReportItemTitle, v.Value from 
    (select r.ReportItemID, r.FormID, r.FieldID, r.Title as ReportItemTitle from 
        (select ReportItemID, ReportID, FormID, FieldID, Title 
            from ReportItems 
            where FormID = '2D6C42E1-0C95-4E40-B792-A17E00C001BF' and ShowInList = 0) r
    JOIN
        (select FormID, FieldID, Title 
            from FormFields 
            where FormID = '2D6C42E1-0C95-4E40-B792-A17E00C001BF') f
        ON r.FormID = f.FormID AND r.FieldID = f.FieldID) rf
LEFT JOIN
    (select FormID, FieldID, Value
        from FormValues 
        where FormID = '2D6C42E1-0C95-4E40-B792-A17E00C001BF' and UserName = '0000000000') v
ON rf.FormID = v.FormID AND rf.FieldID = v.FieldID

FormID                                  FieldID                                 ReportItem's Title  Values
2D6C42E1-0C95-4E40-B792-A17E00C001BF    E7A78AC7-10A4-4752-85D6-A17E00C22EF9    Question's Title    user's 1st question goes here...
2D6C42E1-0C95-4E40-B792-A17E00C001BF    E7A78AC7-10A4-4752-85D6-A17E00C22EF9    Question's Title    user's 2nd question goes here...
2D6C42E1-0C95-4E40-B792-A17E00C001BF    E7A78AC7-10A4-4752-85D6-A17E00C22EF9    Question's Title    user's 2nd question goes here...
2D6C42E1-0C95-4E40-B792-A17E00C001BF    8E1FAC2A-02F1-4D0D-A3E0-A184001484D8    Answer's Title  admin's answer to user's 1st question

笔记:

  • 空答案是未回答的(NULL)。
  • 结果应基于UserNameReportID
  • 所有 ID 都是 GUID
  • 问题和答案都存储在 FormValues 表中

也许我应该使用光标,但我真的很困惑该怎么做。如果有人帮助我,我将不胜感激。

提前谢谢了,

卡多

4

1 回答 1

0

我想我知道你的意思

ReportID    FormID  FieldID Value (Question1)   UserName
ReportID    FormID  FieldID Value (Answer1)     UserName

你想问题和答案在同一个选择栏中吗?您需要按 reportID、FormID、FieldID 排序,并让表示逻辑跟踪当前 id 以嵌套方式显示它(或者您需要一个 orm 工具来为您和用户制作对象模型的映射)

 <ul>
    <li>report1
        <ul>
           <li>form1
               <ul>
                  <li> question1
                      <ul>
                          <li>answer 1 by user 1</li>
                          <li>answer 2 by user 2</li>

……

于 2013-04-28T21:05:35.067 回答